Redirect all http://www.example.com and https://www.example.com traffic to https://example.com. Using Certbot and Nginx

I want to redirect all traffic on www.example.com to example.com.
That is both https and http traffic to all go to https://example.com

How do I achieve that?

I’m using Certbot in my nginx.

Here is my nginx code :arrow_down_small:

server {
server_name www.example.com example.com;

location = /favicon.ico { access_log off; log_not_found off; }
#location /static/ {
#    root /home/jopa/Example/Example;
#}

location / {
    include proxy_params;
    proxy_pass http://unix:/run/gunicorn.sock;
}

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


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

}

1 Like

The port 80 side seems correct and should handle both http://example.com and http://www.example.com.
But the port 443 side needs to handle the case where https://www.example.com.
For that you can add similar code from the port 80 side:

So that:
http://www.example.com > https://example.com [port 80 GOOD]
http://example.com > https://example.com [port 80 GOOD]
https://www.example.com > https://example.com [port 443 MISSING]
https://example.com [port 443 GOOD]

2 Likes

Thanks, It worked.
Port 443 was the one missing.

2 Likes