HTTPS URL无法正确重定向(Nginx)

wqsoz72f  于 2023-05-16  发布在  Nginx
关注(0)|答案(1)|浏览(196)

我有一个不包含www的网站域。我正在努力使用HTTPS获得正确的重定向。
HTTP请求会被正确重定向 ,即http://www.website.com-> https://website.com这是我想要的 *
但是,HTTPS请求没有正确重定向,导致重复页面。
https://www.website.com-> https://www.website.com,但应转到https://website.com *
我相信这是我的Nginx sites_enabled脚本的问题,但我无法弄清楚。

server {
        listen 80;
        server_name website.com www.website.com;
        return 301 $scheme://website.com$request_uri;
}

server {
        listen 443 ssl;

        server_name website.com www.website.com;

        ssl_certificate /etc/nginx/ssl/website.crt;
        ssl_certificate_key /etc/nginx/ssl/website.key;     

        location = /favicon.ico { access_log off; log_not_found off; }
        location /static/ {
                root /home/website/django_webApp/webApp;
        }
        
        location /staticfiles/ {
                root /home/website/django_webApp/webApp;
        }
        
        location / {
                include proxy_params;
                proxy_pass http://unix:/run/gunicorn.sock;
        }
}
ygya80vv

ygya80vv1#

仔细想想这个逻辑。现在,您可以从www.example.com或www.website.com上的HTTP重定向website.com到website.com上的http,然后在这两个域上侦听一个块。如果你在端口80上,你不想重定向到$scheme,你想重定向到https。

server {
        listen 80;
        server_name website.com www.website.com;
        return 301 https://website.com$request_uri;
}

如果你在https://www.website.com,你想重定向到website.com

server {
        listen 443 ssl;
        server_name www.website.com;
        ssl_certificate /etc/nginx/ssl/website.crt;
        ssl_certificate_key /etc/nginx/ssl/website.key;     
        return 301 $scheme://website.com.com$request_uri;
}

最后一个“真实的的”服务器块:

server {
        listen 443 ssl;

        server_name website.com;

        // everything else
}

This unforunately could result in more than one redirect, but is the easiest code to understand. More options are discussed [over here](https://serverfault.com/questions/258378/remove-www-and-redirect-to-https-with-nginx).

相关问题