How to force www or non-www in htaccess

You need to create  a .htaccess file under the webroot directory of your domain and store the following code in it

.

Be sure to replace ‘test.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} ^test.com [NC]
RewriteRule ^(.*)$ http://www.test.com/$1 [L,R=301,NC]

 

#Force non-www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.test\.com [NC]
RewriteRule ^(.*)$ http://test.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.

This entry was posted in Linux. Bookmark the permalink.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.