www and non-www redirect codes for htaccess

The codes below are used to redirect your domain visitors from non-www version to www version of the site or vice versa. These codes are to be added in the htaccess files present in root directory for the domain. If you’re new to the term htaccess, you can read more about it in the post Introduction to .htaccess file.

You can use the following code to redirect your visitors from non-www version of your website to www version

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

The following code does the exact opposite of what the above code does. Basicaly, this will redirect your visitors from www version of your website to non-www version:

#Replace example.com with your domain name
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com [nocase]
RewriteRule ^(.*) http://example.com/$1 [last,redirect=301]

Make sure you change www.example.com and example.com to your domain name. For example: www.errorlog.in and errorlog.in

Save the file and access your website. If it’s not working, it could be caching on the browser. Try accessing it in a private window (incognito) and see if you still have the same issue. If you do, try contacting your hosting provider to see if there’s any caching on the server end.

/ /

Report (Please include link to post while reporting)

Leave a Reply

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