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

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 by AtulHost

Creator of AtulHost. An ardent Linux user. Comes from a business management background. Loves to do research on modern business insights and enterprise solutions like career, education, finance, investments ideas, marketing strategies, and productivity skills; technological trends like automation, artificial intelligence, cloud and edge computing, computer hardware and networking, data science, and the internet of things.

Join the discussion

Required fields are asterisked and email address will not be shared.

Ensure a friendly atmosphere to site members and visitors. Encourage the freedom of expression and exchange of information. Let the discussion meaningful. Comments that are off-topic or spam will be deleted.