[How to] Redirect www URLs to non-www URLs and Vice Versa

by: - Last updated on: December 17th, 2016


Canonicalization remains to be one of the most challenging issues for bloggers aiming for good organic traffic from search engines. Now a days, search engine algorithms are claimed to be smart enough to handle the duplicate content of blogs but still it is wiser to be safe than sorry.

URL canonicalization deals with redirecting www to non-www URLs or vice versa. Popular blogging platforms like Wordpress has seen several plugins which claim to handle URL canonicalization for the webmasters using the 301 permanent redirect. According to itezer, most of these plugins are not helping much to make URL canonicalization effects come away from our blogs, since one version include the functionality of Apache-based redirection, 404 monitoring, and many more.

Redirecting www with Apache

If you see the URL structuring of our blog, it always come sans www. Even if you deliberately all www, it gets redirected to the non-www version. This is done by redirecting the URL with Apache. We use .htaccess file in the root directory of the website/blog. This applies even if the blogs are in the sub-directory.

Here is the code to redirect www to non-www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC] RewriteRule ^(.*) http://%1/$1 [R=301,L]

When you include the domain name, please use the following code

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.com [NC] RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

Here is the code to redirect non-www URLs to www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com
RewriteRule ^ http://www.domain.com%{REQUEST_URI} [L,R=301]

Redirecting www with nginx

For nginx, add the following code to the top of the page. Separate it from the server {} section for the preferred canonical name that you want. Therefore, add the following code when you want to redirect www to non-www:

server {
listen 80;
server_name www.domain.com;
rewrite ^/(.*) http://domain.com/$1 permanent;

What about the code to redirect non-www to www? Here it is

server {
listen 80;
server_name example.com;
rewrite ^/(.*) http://www.example.com/$1 permanent;

I hope this guide helps you to handle URL canonicalization and hence the duplicate content issue in a much better way. Do share your views below.

Weekly Newsletter

Sign up for a specially curated Tech Newsletter.


Leave a Reply

Your email address will not be published.