ScaleScaleScaleScale

Tips / Nginx


Nginx redirection www to non-www and non-www to www

Many times you will need to redirect the main www url to non www, or the opposite, non www to www. This is useful if you need to avoid duplicate content in your Search Engine Optimization. On Nginx we can do that in a few ways.

Nginx Redirect non-www to www

Redirect non-www to www for a single domain
Place this code inside your server block {}:

return 301 $scheme://www.example.com$request_uri;

Example:

server {
   server_name mysite.com;
   return 301 $scheme://www.mysite.com$request_uri;
}

Redirect non-www to www for all your domains
Place this code inside your server block {}:

return 301 $scheme://$1$request_uri ;

Full example in a server block {} to:

server {
   server_name "~^www.(.*)$" ;
   return 301 $scheme://$1$request_uri ;
}

Redirect www to non-www

Redirect www to non-www for a single domain
Place this code inside your server block {}:

return 301 $scheme://mysite.com$request_uri;

Example:

server {
   server_name www.mysite.com;
   return 301 $scheme://mysite.com$request_uri;
}

Redirect www to non-www for all the domains
Place this code inside your server block {}:
return 301 $scheme://www.$host$request_uri;

Example:

server {
   server_name "~^(?!www.).*" ;
   return 301 $scheme://www.$host$request_uri;
}

Do you know any other ways to redirect www to non-www and non-www to www? Please share your tips.

profile

Esteban Borges

Linux Geek, Webperf Addict, Nginx Fan. CTO @Infranetworking

  • I think you mixed up your “Redirect non-www to www for all your domains” and “Redirect www to non-www for all the domains” examples. In the non-www to www you’re matching for www and in the www to non-www you’re matching for non-www.

  • Juan


    server {
    server_name "~^(?!www.).*" ;
    return 301 $scheme://www.$host$request_uri;
    }

    This did not work for me.