How to change htaccess to redirect all non-www links to www pages?

Tag: .htaccess Author: zysdb Date: 2009-10-17

How can I redirect all non-www links to www links? I have found solutions on the internet, but they only redirect the domain name. How do I make this general: http://example.com/testing should redirect to http://www.example.com/testing

Best Answer

try something like this

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

comments:

Ah, didn't realize you can use the server variable in the rewrite rule, that's good.
thanks! could you explain the code a little. i'm new to htaccess and trying to figure this out.
sure, first line obviously enabled URL rewrite on Apache; the second line checks if the host name (domain) starts with www, if it doesn't then the RewriteRule gets executed. The rule is simple - just adds www to the beginning of the host name; R=301 makes this a permanent redirect (for search engine benefits mostly) and L means that this is the last rule in a chain (no RewriteRule after this one would get executed)
The first line enables the rewrite engine. The second line checks the regexp '^www\.' (which means simply www followed by period) against the HTTP_HOST server variable; which effectively contains the domain name of the site the user is visiting. If the domain doesn't contain www. at the beginning (^ means at beginning of the string, and ! before it means that it negates the regexp, so it checks that www. is NOT at start of the string), then it'll simply append the current path to the domain with the prefixed www.
thanks for the excellent descriptions, guys!

Other Answer1

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.yourdomain.com/$1

If you want something generic that works for any domain, you can try something like:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^(.+)$
RewriteRule ^(.*)$ http://www.%1/$1