mod_rewrite - trouble understanding a back reference

Here is my .htaccess, it is in a subfolder of my hosting account.


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

Firstly, I don’t understand how $1 in the rewrite rule back references the text past the url host name? I thought $1 would back reference the entire url - for example: iconcharades.com/index.php?id=blah - since ^(.*)$ matches the entire url right?

Secondly, this rule appears to work sometimes and then sometimes I get a 500 error. Can anybody think of any potential problems with this rule? All i’m trying to do is get rid of www. if it is there.

Thanks heaps.

Nick.

Nick,

I’m not too sure about your Options line but, since you’re not getting a 500 error, it’s okay.

RewriteEngine on is fine as is RewriteCond %{HTTP_HOST} !^iconcharades\.com$ [NC] and it can successfully escape the loop attempted by the RewriteRule’s (.*).

The RewriteRule can ONLY access the {REQUEST_URI} variable, thus, the domain, if used in the regex, will force a NON-match. Ditto any attempt to access the {QUERY_STRING}. In other words, your precept that it matches EVERYTHING is wrong because your EVERYTHING includes the world outside the {REQUEST_URI} string.

What your mod_rewrite code is doing is stripping any and all subdomains from the URL. This can be done slightly more efficiently by NOT capturing the entire {REQUEST_URI} string (you don’t care about a match because {REQUEST_URI} is already available to you) by:

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

Regards,

DK

Excellent answer! Thank you very much.

Nick.