How to Redirect www to non-www with htaccess File

I read a couple days ago that search engines may fetch both www and non-www versions of a domain as separate domains if  redirection is done by using CNAME.  What this means is that you have exactly the same content on two different domains, www and non-www versions of the same domain. This might have negative effects on your rankings on google and other search engines.

So what is the solution? You need to redirect www to non-www or non-www to www version using the http 301 redirection in the htaccess file.

Here is the code for redirecting www to non-www.

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

or you can hardcode your URL if you prefer to.

RewriteCond %{HTTP_HOST} !^yourdomain\.com$ [NC]
RewriteRule ^(.*)$$1 [R=301,L]

Redirecting from Non-WWW to WWW

If you want to redirect from non-www to www, you may try the following code in your htaccess file.

RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ![0-9]{1,3}\.[0-9]{1,3}\.
RewriteRule !"" http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NC]

By the way, don’t forget to include the following directive in your htaccess before adding the above codes.

 RewriteEngine On