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

时间:2020-10-30 10:36:20

标签: nginx redirect webserver

我正在尝试将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域下的所有内容,但似乎不起作用。

您是否有任何提示,为什么这表现不如预期?非常感谢!

1 个答案:

答案 0 :(得分:0)

对于任何有类似问题的人,这就是我最终解决的方式

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; 

}
相关问题