How to force www or non-www versions of your website using .htaccess rules

To force your website to use either “www” or “non-www” versions, simply use the code below in your .htaccess file in the public_html root OR the location of your websites main files. You may need to create the .htaccess file (AKA dot htaccess)

To force www:

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

To force non-www:

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

Note: If you have a CMS such as WordPress or Joomla, you will need to ensure your website settings from your dashboard reflects the above rules that you use.

Help others & share this post!


Leave a comment below