Nginx Rewrite – Redirect from www to Non-www

301-redirectnginx

My nginx file doesn't file is failing and I'm not sure how. I have managed to redirect from http to https fine. But I can't get the www to redirect to non-www version. What am I doing wrong?

server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;

location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
    root /home/sammy/myproject;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/home/sammy/myproject/myproject.sock;
}
# added for let's encrypt
location /.well-known/ {
   root /home/sammy/myproject;
   allow all;
}
}
server {
# SSL configuration

listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
include snippets/ssl-example.com.conf;
include snippets/ssl-params.conf;

    location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
    root /home/myproject/myproject;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/home/sammy/myproject/myproject.sock;
}
# added for let's encrypt
location /.well-known/ {
   root /home/sammy/myproject;
   allow all;
}
}

I tried this additional block:

server {
listen 80;
server_name www.example.com;
return 301 https://$server_name$request_uri;
...
}

This didn't seem to work though. I thought perhaps I should change this to listen on 443, but wasn't sure how that would affect the ssl server block and default_server directive?

Best Answer

The $server_name refers to the server name you have defined in the virtual host block. Therefore your additional block causes a redirect cycle redirecting back to itself.

You have to use a literal domain name there instead of a variable.

For SSL domain with www, you have to add listen 443 ssl; to the block and certificate values.

So, this should be your third block:

server {
    listen 80;
    listen 443 ssl;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
    include snippets/ssl-example.com.conf;
    include snippets/ssl-params.conf;
    ...
}