如何使用 NGINX 将 80 重定向到 443,以及为什么它似乎使用两个服务器块?

如何使用 NGINX 将 80 重定向到 443,以及为什么它似乎使用两个服务器块?

我的 NGINX 配置如下

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /run/nginx.pid;
events {
    worker_connections 1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       443 ssl default_server;
        listen       [::]:443 ssl default_server;
        include      snippets/self-signed.conf;
        include      snippets/ssl-params.conf;
        server_name  _;
        location / {
          proxy_pass http://localhost:3000;
        }
    }
    server {
        listen 80;
        listen       [::]:80;
        server_name  _;
        if ($scheme = http) {
           return 301 https://$host$request_uri;
        }
    }
}

但是当发生以下情况时……

[ec2-user@ip-172-31-45-134 nginx]$ curl https://secondave.net --insecure
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.22.1</center>
</body>
</html>

它工作正常但如果我注释掉它就不会重定向return 301 https://$host$request_uri;

我缺少了什么,怎样才能同时拥有这两者?

我也尝试过这么做...

[ec2-user@ip-172-31-45-134 next-site]$ curl -L https://secondave.net --insecure
curl: (47) Maximum (50) redirects followed

另一件奇怪的事情是,代理似乎也发生了同样的事情

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       443 ssl default_server;
        listen       [::]:443 ssl default_server;
        include      snippets/self-signed.conf;
        include      snippets/ssl-params.conf;
        server_name  _;
        location / {
          proxy_pass http://localhost:3000;
        }
    }
    server {
        listen 80;
        listen       [::]:80;
        server_name  _;
        location / {
          proxy_pass http://localhost:3000;
        }
    }      
}

有效,但是

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       443 ssl default_server;
        listen       [::]:443 ssl default_server;
        include      snippets/self-signed.conf;
        include      snippets/ssl-params.conf;
        server_name  _;
        location / {
          proxy_pass http://localhost:3000;
        }
    }
    server {
        listen 80;
        listen       [::]:80;
        server_name  _;
    }     
}

没有正确代理

答案1

无论是什么导致了循环(为了使 HTTPS 流量再次重定向到 HTTP 并遵循 301 返回规则),您都可以通过if向规则中添加以下内容来阻止它:

if ($scheme = http) {
return 301 https://$host$request_uri;
}

答案2

看起来 SSL 服务器块中的行仍在将请求传递给不安全的 URL。

改变proxy_pass http://localhost:3000;

proxy_pass https://localhost:3000;

相关内容