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

— Published on: September 26th, 2015

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!

Published in Science and Technology

About AtulHost

Hi, I'm Atul Kumar Pandey; also known as AtulHost on the web, a blogger by profession with an objective of sharing fresh and real contents in the business and technical topics; from contents to useful resources it's all here.

Leave a Reply

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