Nginx仅将服务器的特定路径从http重定向到https

时间:2020-04-27 09:53:03

标签: windows nginx http-redirect

我想将路径从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将所有到达本地服务器上端口80的HTTP请求重定向到HTTPS。

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

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

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的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

第二个服务器块中的此部分不起作用。因为它再次重定向到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/;

现在可以正常工作了。

相关问题