如何在Nginx中使用https重定向将www重定向到裸域?

时间:2019-08-21 14:33:24

标签: linux nginx

我的网站当前正在将HTTP重定向到HTTPS,但是我希望将www.example.com/page的任何请求重定向到example.com/page。

理想情况下,我只希望从http://www.example.comhttps://example.com进行一次重定向,而不是: http://www.example.com 301至https://www.example.com 301至https://example.com

但如有必要,我可以进行两次重定向。

我已经尝试过了,但是没有用:

/ etc / nginx / sites-enabled / example

server { server_name www.exmaple.com; return 301 $scheme://example.com$request_uri; }

这是文件的其余部分:

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

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/name/example-main;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/name/example-main/example.sock;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Ce$
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by $
    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://$host$request_uri;
    } # managed by Certbot


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




}

server { server_name www.example.com; return 301 $scheme://example.com$request_uri; }

提前感谢您的提示。

1 个答案:

答案 0 :(得分:0)

尝试从配置文件中删除最后一行

server { server_name www.example.com; return 301 $scheme://example.com$request_uri; }

然后使用“ nginx -t”命令检查配置,并使用“ service nginx reload”重新加载配置。