【问题标题】:Nginx redirect only specific paths of a server from http to httpsNginx 仅将服务器的特定路径从 http 重定向到 https
【发布时间】:2020-08-10 20:15:13
【问题描述】:

我想将路径从 http 重定向到 https,如下所示:

我有一个配置文件:

worker_processes  1;


events {
    worker_connections  1024;
}


http {

server {
        listen 80;
        listen [::]:80;

        server_name localhost;

        return 301 https://$host$request_uri;
}

# HTTPS server
server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;     

        ssl_certificate certs/myservice.crt;
        ssl_certificate_key certs/myservice.key;

        server_name myservice.com localhost;

        location /api/ {

                proxy_set_header X-Real-IP $remote_addr;
                proxy_pass https://localhost:55555/api/;

                client_max_body_size 500G;

                proxy_connect_timeout       300;
                proxy_send_timeout          300;
                proxy_read_timeout         3600;
                send_timeout                300;

        }

        location / {

                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;

                proxy_pass http://localhost:80/;

                client_max_body_size 500G;

                proxy_connect_timeout       300;
                proxy_send_timeout          300;
                proxy_read_timeout         3600;
                send_timeout                300;

        }
        location ~ /\.ht {
                deny all;
        }
}
}

当我尝试这样做时,第二个要求得到了满足。但是保持http://localhost:80/ 不变的第一个失败了。它被不必要地重定向为https://localhost

简而言之,nginx 会将所有来自 localhost 服务器上端口 80 的 HTTP 请求重定向到 HTTPS。

我还尝试从第二个服务器块中删除 location / { } 部分。

然后尝试在第一个服务器块中指定为:

server {
        listen 80;
        listen [::]:80;

        server_name localhost;

        location / {
            proxy_pass http://localhost:80/
        }

        location /api/ {
            return 301 https://$host$request_uri;
        }
}

他们两个都没有工作。

在 Nginx 中仅将服务器的特定路径从 http 重定向到 https 的正确方法是什么?

【问题讨论】:

    标签: windows nginx http-redirect


    【解决方案1】:

    第二个服务器块中的此部分不起作用。因为它再次重定向到 https。

    location / {
    
                    proxy_set_header Host $host;
                    proxy_set_header X-Real-IP $remote_addr;
    
                    proxy_pass http://localhost:80/;
    
                    client_max_body_size 500G;
    
                    proxy_connect_timeout       300;
                    proxy_send_timeout          300;
                    proxy_read_timeout         3600;
                    send_timeout                300;
    
            }
    

    因此将该应用程序暴露给 80 以外的其他主机端口,例如 88。然后将此 proxypass URL 更改为:

     proxy_pass http://localhost:88/;
    

    现在可以正常使用了。

    【讨论】:

      猜你喜欢
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      • 2018-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多