htaccess domain redirection www to non-www and the other way around code examples

The search ranking of your domain can go down If your website is accessible with and without www as both URLs with same contents are indexed by search engines and can cause duplicate contents issues.
In this case, all you need to do is either redirect your www subdomain to non-www (naked domain) or the other way around.
You can easily redirect your domain using a RewriteRule in htaccess or server.config file.
In this post I will show you how to redirect a domain using htaccess. You can simply copy and paste the code to your htaccess file from this post.





non-www to www





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


Explanations : The first line RewriteEngine on tells server to turn on the engine for rewriting URLs.
The second line is a condition for the rule RewriteCond %{HTTP_HOST} ^example.com$ [NC] here we match against the host header using "example.com" string. The NC flag makes the host match case-insenstive .
The third line RewriteRule (.*) http://www.example.com%{REQUEST_URI} [L,R=301] redirect all urls to www version of the domain. The rule is triggered only if the condition is met meaning that if the host header is example.com .




non-www to www generic rule


If you have more then one domain to redirect from non-www format to www you can use a generic rule that checks http_host header dynamically. You can use a regex based pattern something like the following:



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

The rule above will redirect all non-www hosts to www. The %1 variable contains the host value captured in the RewriteCond regex. The rule will also enforce www on subdomains, if you do not want your subdomain to redirect to www , put an additional condition above the RewriteCond ie : RewriteCond %{HTTP_HOST} !^foo.example.com$ [NC] excludes foo.example.com subdomain from the rule. You can add as many conditions as you want but put them just before the main RewriteCond.



www to non-www





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


With the above rule your www subdomain will redirect to non-www root domain.



www to non-www generic rule






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


Post a Comment

0 Comments