Nginx Remove WWW And Respond To Both Nginx Remove WWW And Respond To Both nginx nginx

Nginx Remove WWW And Respond To Both


According to https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#server-name-if, you should use:

server {  server_name www.example.com;  return 301 $scheme://example.com$request_uri;}server {  server_name example.com;  # [...]}


I believe it's better to add two seperate server blocks to avoid unnecessary checking by the if block. I also use the $scheme variable so that HTTPS requests will not be redirected to their insecure counterparts.

server {    listen 80;    server_name www.mydomain.io;    rewrite ^ $scheme://mydomain.io$uri permanent;}server {    listen 80;    server_name mydomain.io;    # your normal server block definitions here}


Another way to code it :

if ($http_host ~* "^www\.(.+)$"){    rewrite ^(.*)$ http://%1$request_uri redirect;}

It works even with multiple domain names on the same code.