HTTPS www to non-www on NGINX HTTPS www to non-www on NGINX nginx nginx

HTTPS www to non-www on NGINX


OK, so I figured this out a while ago but forgot to post the answer, so here it is.

server {    listen 80;    server_name www.example.com example.com;    return 301 https://example.com$request_uri;}server {    listen 443 ssl;    server_name example.com;    root /home/forge/default/public;    if ($host = 'www.example.com') {        rewrite ^/(.*)$ https://example.com/$1 permanent;    }}

How robust this is I'm not entirely sure but it works.

Essentially, you listen on port 80 for www and non-www and return a 301 redirect to the secure non-www URL. You then check in your SSL server block listening on port 443 if the host that has been requested matches the www version of the secure URL and if it does you permanently rewrite it to the secure non-www version.


nginx takes SSL-certificate from 'default_server' or from first described for the particular IP+port pair.

So, you should

  • swap SSL-enabled server blocks
  • or just add default_server parameter to listen directive in your second block.