Matching Digits in a mod_rewrite RewriteRule

Album Cover: The Black Album

"Young enough to know the right car to buy yet grown enough not to put rims on it."
Jay-Z / 30 Something

Posted on January 15, 2008 1:49 PM in Web Development

If you read up on the syntax of RewriteRule in Apache's mod_rewrite support, you may be led to believe that the full extent of Perl Regular Expressions is supported. After all, the following shows up verbatim in the RewriteRule documentation:

For more information about regular expressions, have a look at the perl regular expression manpage ("perldoc perlre").

However, I've found that it just isn't so. In an attempt to match a string of digits in a request and redirect to a page when the condition is met, I did something like the following:

RewriteRule ^\d\d\d /flames/ [L]

If working properly, a request to http://www.example.com/666 would redirect to http://www.example.com/flames/. However, it wasn't doing what I wanted to. I even tried using ^\d{3} as my pattern, but no dice.

As it turns out, it appears that mod_rewrite prefers character sets in RewriteRule patterns. Therefore, the following works as expected:

RewriteRule ^[0-9]{3} /flames/ [L]

So if you're trying to match numbers/digits in a RewriteRule, be sure to use a character set instead of the \d digit shortcut so you can avoid wasting half-an-hour of your time like I just did.

Comments

Jemima on January 25, 2008 at 5:51 AM:

Thank you! You just saved me half an hour :-)

Permalink

Post Comments

If you feel like commenting on the above item, use the form below. Your email address will be used for personal contact reasons only, and will not be shown on this website.

Name:

Email Address:

Website:

Comments:

Check this box if you hate spam.