[thelist] mod_rewrite question

Mark Groen evolt at markgroen.com
Tue Aug 19 22:11:02 CDT 2008

On Tuesday 19 August 2008 17:31:18 Shannon Hubbell wrote:
> ........redirecting mydomain.com to www.mydomain.com. This is
> what I'm using:
> RewriteEngine on
> RewriteCond %{HTTP_HOST} ^mydomain.com [NC]
> RewriteRule ^(.*)$ http://www.mydomain.com/$1 [L,R=301]
> That's the way it is right now, although I've tried several variations.
> This has no effect.

Test the Apache {HTTP_HOST} variable to see if the www. is already there and, 
if it's not, redirect to the desired host name:

RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule .? http://www.example.com%{REQUEST_URI} [R=301,L]

To denote that {HTTP_HOST} is an Apache variable, prepend a % character to it. 
The regex begins with the ! character, which will cause the condition to be 
true if it doesn't match the pattern. Also have to escape the dot character 
so that it matches a literal dot and not any character, as is the case with 
the dot metacharacter. Also added the No Case flag to make this operation 

The RewriteRule will match zero or one of any character, and will redirect to 
http://www.example.com plus the original {REQUEST_URI} value. The R=301, or 
redirect, flag will cause Apache to issue a HTTP 301 response, which 
indicates that this is a permanent redirection; the Last flag tells 
mod_rewrite that you've completed this block statement.

I plagiarized this from Sitepoint, more about mod_rewrite:

Another good place for real world examples:


More information about the thelist mailing list