Updated mod rewrite on Apache Redirection Page
This entry was posted on 4/23/2007 1:38 PM and is filed under General.
We have just updated the
Working with Apache Redirection page to include more working examples using mod rewrite. The "how it works" details have also been expanded so the viewer can better learn from the examples and be better prepared to modify the examples to suit their needs.
We also added an example showing how to get a server error 500 and details on why it happened, also in keeping the users interests in mind.
One common question I get is "How do I redirect from a non www URL to a www URL? When I searched the web I found numerous examples but with little explanation as to how they worked. When I tested the various versions I got... well, various results. Some of them unpleasant!
Most just plain didn't work or work in all situations.
Others threw the server into a tizzy winding up with the dreaded error 500.
A few actually worked as advertised. I'll include a tweaked version here for the benefit of all:
<IfModule rewrite_module>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(.*)
http://www.example.com/$1 [R=302,L]
</IfModule>
This version goes in the server or virtual host context.
It will temporarily redirect any domain request that is not
www.example.com to
www.example.com.
If you want this redirection to be permanent, change the 302 to a 301.
If you want to use this in the .htaccess context just remove the <IfModule> and </IfModule> directives.
Also be sure FollowSymLinks is in effect in your context. I have tested and currently use this version on my server so I have undeniable proof it works!
Hope this makes it easier for someone else to find than it was for me.
If you want the details on how this works, please use the Working with Apache Redirection link topside to get to the article.
Any questions, complaints or whatever?, Please feel free to leave a comment or two.
Enjoy!