Nginx redirect http://www and naked http/https to https://www

前端 未结 4 981
暖寄归人
暖寄归人 2021-01-02 12:16

I would like to redirect all traffic from the following domains:

  • http://domain.com
  • http://www.domain.com
  • http
4条回答
  •  时光说笑
    2021-01-02 13:01

    Provide a specific server block for the naked domain along with a general default. The more-specific ones will be used first.

        server {
                listen 80;
                listen [::]:80;
                listen 443 ssl http2;
                listen [::]:443 ssl http2;
                server_name example.com;
    
                return 301 https://www.$host$request_uri;
        }
        server {
                listen 80 default_server;
                listen [::]:80 default_server;
    
                return 301 https://$host$request_uri;
        }
        server {
                listen 443 ssl http2;
                listen [::]:443 ssl http2;
                server_name www.example.com;
                # omitting the rest for https://www.example.com
        }
    

    I use Let's Encrypt for my certificates so something like the following for default_server prevents redirecting the ACME challenges (note the second wildcard server_name for handling all https://*.example.com which don't have their own server block).

        # omit server_name example.com block, same as above
        server {
                listen 80 default_server;
                listen [::]:80 default_server;
    
                location ~ ^/\.well-known/acme-challenge {
                    # LetsEncrypt
                    add_header Content-Type text/plain;
                    expires 0;
                    alias /var/www/html/acme/$host;
                    break;
                }
                location ~ ^/(?!\.well-known/acme-challenge) {
                    return 301 https://$host$request_uri;
                }
        }
        server {
                listen 443 ssl http2;
                listen [::]:443 ssl http2;
                server_name *.example.com;
                # omitting the rest for https://*.example.com
        }
    

    Setup certificates for the naked example.com, www.example.com and any others:

    sudo certbot certonly --manual -d example.com -d www.example.com -d abc.example.com

提交回复
热议问题