Nginx - 非 www 到 www 重定向不适用于子文件夹

Nginx - non-www to www redirect not working for subfolders

我正在尝试将 example.com/.* 下的所有内容重定向到 www.example.com/..。通过调整 Nginx.

中启用站点的设置

我设法让它只适用于主页,但是当我尝试访问像 example.com/es/ 这样的子文件夹时,这并没有重定向到 www.example.com/es/

这些是我当前的设置:

server {
        server_name example.com www.example.com;

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

        location /core/static {

        alias /home/andrea/agency/core/static/;

    }


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

    listen 443 ssl; # managed by Certbot
    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


}
server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = example.com) {
        return 301 https://www.$host$request_uri;
    } # managed by Certbot


        listen 80;
        server_name example.com www.example.com;
    return 404; # managed by Certbot


}

虽然 $request_uri 部分会处理 non-www 域下的所有内容,但它似乎不起作用。

您是否有任何提示为什么这没有按预期运行?非常感谢!

对于遇到类似问题的人,这就是我最终解决的方法

server {
  
    if ($host = example.com) {
        return 301 https://www.example.com$request_uri;
    }

    server_name example.com www.example.com;

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

    location /core/static {

        alias /home/andrea/agency/core/static/;

    }

    location / {

        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }


    listen 443 ssl; 
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; 
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; 
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; 

}

server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    }


    if ($host = example.com) {
        return 301 https://www.example.com$request_uri;
    } 

    server_name example.com www.example.com;
    listen 80;
    return 404; 

}