Apache mod_rewrite URLs Also Provide Validation

February 17, 2005

I Realized something when using Apache mod_rewrite for search engine safe url's, they also provide input type validation. I can use mod_rewrite to ensure that only integers are passed in my url in the id.

For example, on my site macread I use url's like: http://macread.com/feed/22 instead of something like http://macread.com/feed.cfm?id=22. The nice side effect I have discovered to using Apache mod_rewrite to do this, is that your RewriteRules can also provide input validation.

I normally have to write a lot of code to ensure that people aren't trying to pass letters to throw errors, or injecting SQL into my urls, but with mod_rewrite, this validation is almost automatic, and if the validation fails, the user gets a 404!

Here's the code I use for search engine safe url's with Apache:

RewriteEngine On
RewriteRule ^/news/([0-9]+)/?$ /news.cfm?id=$1 [PT,L]

This rule matches only the numbers 0-9 after /news/, it also allows an optional / at the end. If the pattern is not matched, a 404 page is returned.

If you are in-fact going to let apache be the only form of validation, you will also want to block direct access to your file. You can do that with this rule:

RewriteRule ^/news.cfm.* / [F,L]

The above code will respond with a 403 Forbidden response when someone tries to access /news.cfm directly.

Like this? Follow me ↯

You might also like:

5 people found this page useful, what do you think?

Foundeo Inc.