GTS Joe
GTS Joe

Reputation: 4152

Nginx Redirect All Non-www Traffic to www on Ports 80 and 443

My Nginx server block is currently configured to serve both non-www and www traffic. How can I configure my server block to:

http://example.com should go to: https://www.example.com

https://example.com should go to: https://www.example.com

Here is what I currently have:

server {
    root /var/www/example.com;
    index index.html index.htm index.nginx-debian.html index.php;

    server_name example.com www.example.com;

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

    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://$host$request_uri;
    } # managed by Certbot


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


    listen 80;
    listen [::]:80;

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

Upvotes: 1

Views: 1270

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15478

Split your SSL server block by two:

server {
    server_name example.com;
    listen [::]:443 ssl; # 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

    return 301 https://www.example.com$request_uri;
}
server {
    server_name www.example.com;
    listen [::]:443 ssl; # 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

    root /var/www/example.com;
    index index.html index.htm index.nginx-debian.html index.php;
    location / {
            try_files $uri $uri/ =404;
    }
}

Leave the server block that listen on port 80 as is.

Upvotes: 2

Related Questions