简体   繁体   中英

Nginx redirect all traffic to HTTPS and non-www

have what I thought was a simple issue but cannot figure it out. My goal is to have HTTPS non-www.

NON-HTTPS traffic is being redirected properly, but the last one I cannot figure out is to redirect HTTPS www traffic to HTTPS non-www.

Working:
http://example.com -> https://example.com  
http://www.example.com -> https://example.com 
https://example.com (no redirect needed)

Not Working:
https://www.example.com -> https://example.com (not working)

server {

        root /var/www/example.com/;
        index index.php index.html index.htm;

        server_name example.com www.example.com;

        location / {
                try_files $uri $uri/ =404;
        }
        location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.3-fpm.sock;
    }


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


    if ($host = example.com) {
        return 301 https://example.com$request_uri;
    } # managed by Certbot
        listen 80;
        listen [::]:80;

        server_name example.com www.example.com;
    return 404; # managed by Certbot
}

So I was missing the if statement in the SSL server block

Added:

if ($host = www.example.com) {
        return 301 https://example.com$request_uri;
    } # managed by Certbot

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