Forum Moderators: buckworks & webwork

Message Too Old, No Replies

Use [NC] in your rewrite rules

That last little detail...

         

jtara

11:57 pm on Oct 2, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes, it's yet another mod_rewrite post! Gotta be the most posted-about topic on WebmasterWorld...

When researching "the best way" to do redirects of secondary domains (www or non-www, depending on your viewpoint, additional domains, etc.) I noticed the use of [NC] in the RewriteCond in a few cases, and wondered what that was about.

It hadn't been mentioned in one of the better threads on the subject:

[webmasterworld.com...]

It was used in another:

[webmasterworld.com...]

but never explained. In fact, it drew an unchalenged comment saying:

Not sure why you'd want the [NC] flag on the first RewriteCond...

Here's why.

Let's say your primary site is example.com. You also have www.myexample.com, which you want to redirect to the primary site. (Just reverse these if you prefer the "www" convention for primary.)

Now, what happens if a user types "www.MyExample.com" in their URL bar?

If you don't use [NC], it won't be redirected!

Without [NC], mod_rewrite does a CASE-SENSITIVE match on the hostname. If any letter doesn't match case, the condition will not match.

This is probably particulary of interest to people in this forum, as there's probably a higher prevelance of WordWord.tld type of domain-names, and the temptation is there for the user to capitalize when typing-in these domains.

FWIW, here's my current formula:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(www\.)?example\.(biz¦com¦info¦net¦org¦us)$ [NC]
RewriteRule ^/robots.txt$ /robots_other.txt [L]

RewriteCond %{HTTP_HOST} ^(www\.)?example\.(biz¦com¦info¦net¦org¦us)$ [NC]
RewriteRule ^/(.*) http://example.com/$1 [L,R=301]

jtara

12:20 am on Oct 3, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, it turns out you DON'T need the [NC] in the example above that elicited the "why would you need that" comment.

The reason is the use of! (the "not" operator). This is probably a better way to a "catch-all" redirect, anyway, and a great way to do things for domainers, who might be hosting a large number of domains all directing to the same content or script.

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

If the host is NOT exactly "example.com", then the redirect is taken. Nice thing about this construction is that you do not have to exhaustively list domains.

Webwork

11:43 am on Oct 3, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Thanks for clearing that up jt. ;)