简体   繁体   中英

How to redirect from http://www.* to https://* in Nginx?

So I am trying to achieve 4 things:

  • support both ip-v4 and ip-v6
  • support letsencrypt ssl certificates (the acme-challenge location in http)
  • redirect www to non www
  • redirect http to https

I have come up with a config, but it seems not to work. I get a "page does not exist" when trying to access http://www.MY_DOMAIN.COM . Due to the hsts setting, this does work after having visited the https non-www version once.

Note that I have ssl certificates for both the with and without www domain.

How can I achieve this / what am I doing wrong in my config:

# HTTP server
#
server {
    listen [::]:80;
    server_name MY_DOMAIN.COM www.MY_DOMAIN.COM;

    location /.well-known/acme-challenge {
        root /var/www/letsencrypt;
        try_files $uri $uri/ =404;
    }

    location / {
        return 301 https://MY_DOMAIN.COM$request_uri;
    }
}
# HTTPS server
#
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name www.MY_DOMAIN.COM;

    ssl on;
    ssl_certificate         /etc/letsencrypt/live/www.MY_DOMAIN.COM/fullchain.pem;
    ssl_certificate_key     /etc/letsencrypt/live/www.MY_DOMAIN.COM/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/www.MY_DOMAIN.COM/fullchain.pem;

    ssl_session_cache shared:SSL:50m;
    ssl_session_timeout 5m;
    ssl_stapling on;
    ssl_stapling_verify on;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    add_header Strict-Transport-Security "max-age=86400; includeSubDomains";

    return 301 https://MY_DOMAIN.COM$request_uri;
}

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server ipv6only=on;
    server_name MY_DOMAIN.COM;

    ssl on;
    ssl_certificate         /etc/letsencrypt/live/MY_DOMAIN.COM/fullchain.pem;
    ssl_certificate_key     /etc/letsencrypt/live/MY_DOMAIN.COM/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/MY_DOMAIN.COM/fullchain.pem;

    ssl_session_cache shared:SSL:50m;
    ssl_session_timeout 5m;
    ssl_stapling on;
    ssl_stapling_verify on;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    add_header Strict-Transport-Security "max-age=86400; includeSubDomains";

    root /var/www/MY_DOMAIN.COM;
    index index.html;
}

Also, I do not find the copy-paste nature of the two server blocks very nice.

As @RichardSmith notes; I was not listening to the ipv4 version of the http://www variant. Hence, the redict was not triggered at all.

After fixing this, the setup is working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM