www in htaccess

Many customers at some point request to force either the www or non-www version of their site to display in their visitor’s browser. For example always have www.example.com or simply example.com display in their visitor’s web browser. There is a common thought that forcing one format is better for search engine optimization.

How to force www or non-www in htaccess

Be sure to replace ‘example.com‘ with your actual domain name. NOTE: do not place both selections of code in the file as it will cause an error. 

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

 

#Force non-www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

Now, when you type in your domain name with either www in front or not, it should display as you have set it in the .htaccess file.

© inmotionhosting.com

Leave a Reply

Your email address will not be published.

*