Nginx - how to redirect (301) www to non-www corre

2019-07-13 06:35发布

With the following Nginx config file, I currently can redirect permanently all HTTP www request to HTTPS non-www . http://www.example.com => https://example;com

All HTTPS non-www request ar well handed .. https://example.com

But, www HTTPS request are NOT redirected to non-www HTTPS https://www.examples.com --> https://www.examples.com I'ld like to have : https://www.examples.com --> https://examples.com

what's missing in my config ? thanks for feedback

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条回答
叛逆
2楼-- · 2019-07-13 07:08

Nothing in your configuration handles redirecting https://www.example.com to https://example.com (but you knew that).

Assuming that your certificate is valid for www.example.com, you could create a separate server block for port 443 and mark it as a default_server (such as you already have for port 80).

In fact you could combine everything that isn't https://www.example.com into a single server block:

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;
    ...
}

See this document for details.

查看更多
登录 后发表回答