【问题标题】:Nginx - how to redirect (301) www to non-www correctly for bot http /https?Nginx - 如何为bot http / https正确重定向(301)www到非www?
【发布时间】:2016-12-27 14:41:23
【问题描述】:

使用以下 Nginx 配置文件,我目前可以将所有 HTTP www 请求永久重定向到 HTTPS non-www 。 http://www.example.com => https://example;com

所有 HTTPS 非 www 请求都处理得当.. https://example.com

但是,www HTTPS 请求不会重定向到非 www HTTPS https://www.examples.com --> https://www.examples.com 我想拥有: https://www.examples.com --> https://examples.com

我的配置中缺少什么? 感谢反馈

default.conf

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

server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name www.example.com;
        return 301 $scheme://example.com$request_uri;
}

server {
       listen 443 ssl http2 default_server;
       listen [::]:443 ssl http2 default_server;
       server_name example.com;
       include snippets/ssl-example.com.conf;
       include snippets/ssl-params.conf;

       root /var/www/html;
       index index.html index.htm;

       location / {
         try_files $uri $uri/ =404;
       }
}

【问题讨论】:

    标签: nginx


    【解决方案1】:

    您的配置中没有任何内容处理将https://www.example.com 重定向到https://example.com(但您知道这一点)。

    假设您的证书对 www.example.com 有效,您可以为端口 443 创建一个单独的 server 块并将其标记为 default_server(例如您已经拥有端口 80)。

    事实上,您可以将不是https://www.example.com 的所有内容组合成一个server 块:

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
        listen 443 ssl http2 default_server;
        listen [::]:443 ssl http2 default_server;
        include snippets/ssl-example.com.conf;
        include snippets/ssl-params.conf;
    
        return 301 https://example.com$request_uri;
    }
    
    server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name example.com;
        include snippets/ssl-example.com.conf;
        include snippets/ssl-params.conf;
        ...
    }
    

    详情请见this document

    【讨论】:

    • 非常感谢!是的,我的证书对 bot www 和 no-www 有效。我想过,但完全忘记将 sn-ps 放在两个块上...
    猜你喜欢
    • 2015-10-23
    • 2018-10-19
    • 2018-02-02
    • 1970-01-01
    • 2019-08-12
    • 2019-02-04
    • 2017-09-03
    • 2016-01-07
    • 2018-04-22
    相关资源
    最近更新 更多