一个 Nginx 301 重定向到 HTTPS + 带有 WWW 子域名

一个 Nginx 301 重定向到 HTTPS + 带有 WWW 子域名

我不知道我做错了什么。我已经删除了一个默认文件条目来自/etc/nginx/sites-enabled并且只有一个启用的站点:

server {
    listen              80;
    listen              443 ssl;
    server_name         example.com;
    
    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot

    return 301          https://www.$server_name$request_uri;
}

server {
    listen              443 ssl;
    server_name         www.example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot

    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    location = /favicon.ico { access_log off; log_not_found off; }

    location /static/ {
        root /django/example;
    }

    location /media/ {
        root /django/example;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/mydomain.sock;
    }
}

当我尝试 CURL 测试时,它仍然会执行两次 301 重定向,而不是一次。它首先从http 到 https然后访问 www:

HTTP/1.1 301 Moved Permanently
Date: Tue, 24 Nov 2020 13:29:24 GMT
Connection: keep-alive
Cache-Control: max-age=3600
Expires: Tue, 24 Nov 2020 14:29:24 GMT
Location: https://example.com/
...
...
Server: cloudflare

HTTP/2 301 
date: Tue, 24 Nov 2020 13:29:24 GMT
content-type: text/html
set-cookie: __cfduid=d750a6e7c1d415accb428ff6431220db01606224564; expires=Thu, 24-Dec-20 13:29:24 GMT; path=/; domain=.example.com; HttpOnly; SameSite=Lax; Secure
location: https://www.example.com/
cf-cache-status: DYNAMIC
...
...
server: cloudflare

HTTP/2 200 
date: Tue, 24 Nov 2020 13:29:25 GMT
content-type: text/html; charset=utf-8
set-cookie: __cfduid=d075d1d072fd35d4ec365037a68bb30cdb608224565; expires=Thu, 24-Dec-20 13:29:25 GMT; path=/; domain=.example.com; HttpOnly; SameSite=Lax; Secure
...
...
server: cloudflare

我的 nginx 配置有问题吗?是否可以从http 和非 wwwhttps + www

感谢您的任何建议!

相关内容