Redirect www to non-www or non-www to www using htaccess RewriteRule with code examples

A domain with www and without it can cause duplicate contents issues on search engines unless these two versions are  pointing to each other. If your domain is accessible with both www and non-www   then you are missing  an important point of SEO.  Search engines will think that these are two different domains serving the same contents and can prevent your domain from being properly indexed in their database.

To fix this, you can either redirect your naked domain ie to or the www subdomain to

Redirect non-www to www using htaccess or server.config files

With mod-rewite rules in htaccess or server.config files you can easily redirect a non-www domain to  its www version.
The following is a 100% working code you can just copy and paste to your htaccess or server.config file :

RewriteEngine on
#1) redirect a non-www domain to www
RewriteCond %{HTTP_HOST} !^www [NC]
RewriteRule (.+) http://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

To test this rule , paste it to your public_html/.htaccess or server.config  file, and visit your non-www website URL  . The rule will change your URL  :


The rule above  applies to any domain  that doesn’t begin with www  . This will also redirect  your subdomains to include www ie will get redirected to . To prevent this from happening, you can use a domain specific rule .
The following rule will only redirect your “” domain  to “” :

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

Make sure to replace with your domain name in the Rule example above.
This will redirect your :


One of the benefits of using domain specific rule is that it won’t conflict with your other domains. Only the domain you put in the RewriteCond will get affected by the rule.

Redirect www to non-www

The rule to redirect your www domain to non www is same as we used to redirect non to www but there are some slight changes in RewriteCond and the destination URL .
To enforce non www on your domain, you could use the following rule in your htaccess or server.config file :

RewriteEngine on
#redirect www to non-www
RewriteCond %{HTTP_HOST} ^www.(.+) [NC]
RewriteRule (.+) http://%1%{REQUEST_URI} [NE,L,R=301]

Leave a Reply

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