Nginx Redirection Non-www to www and www to Non-www

Published in

on

Sometime we will need to redirect the main non www to www, or the vice versa, www to non www url. This Nginx Redirection is useful if you need to avoid duplicate contents in your Search Engine Optimization methods because Google consider a site with www and non-www two different sites. So on Nginx we can do that in a few ways. There are many ways we can force Nginx to use either www version or non-www version of URLs for your site.

NGINX Redirection www non www and Vice Versa

We use following codes all the time for our clients and friends.

Redirect from Non-www to www

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

Redirect from www to Non-www

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

In both the scenario, for other-www, we create a altogether different server { … } block. This is cleanest and optimised way to handle www to non-www and non-www to www redirection.

There are some WordPress plugins available there which can handle this at PHP-level. But for performance reason, always handle things in Nginx, that can be handled in Nginx alone!

Leave a Reply

Your email address will not be published. Required fields are marked *