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
+4
A:
try something like this
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Marek Karbarz
2009-11-02 08:03:44
Ah, didn't realize you can use the server variable in the rewrite rule, that's good.
reko_t
2009-11-02 08:07:16
thanks! could you explain the code a little. i'm new to htaccess and trying to figure this out.
chris
2009-11-02 08:20:14
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)
Marek Karbarz
2009-11-02 08:40:35
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.
reko_t
2009-11-02 08:41:52
thanks for the excellent descriptions, guys!
chris
2009-11-02 09:19:29
+2
A:
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
reko_t
2009-11-02 08:05:53