Blog: mod_rewrite and Ignoring Directories

Views:
8837

So i have my little website and like a lot of websites, I have one index page that I simply pass a parameter through a GET request and that determines the output of the site. With all the push for website recognition, SEO, etc., I thought it was time to tidy things up a bit.

So I go and do some research on Apache's mod_rewrite [http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html] and whip up a simple rewrite rule that I found to work just great:

RewriteEngine on
RewriteRule ^([A-Za-z0-9-]+)$ index.php?req=$1 [L]

Works great, right? So I punch in something like:

www.mysite.com/contact

and it kindly rewrites it and takes me to:

www.mysite.com/index.php?req=contact

Awesome! .... Or so I thought.

Now being a good little developer, I have a bunch of random garbage on my website. Nothing fantastic, just little things I've written over the years. And they're all located at URLs like:

www.mysite.com/applicationX

So I go to one of those today and find out that my stupid little rewrite rule tries to rewrite my directory names as well! AHH!

Not to fear! Behold the solution:

RewriteCond %{REQUEST_FILENAME} -f [NC,OR]
RewriteCond %{REQUEST_FILENAME} -d [NC]
RewriteRule .* - [L]

Place that wonderful little rule above the rule you're attempting to execute, or simply at the top of your .htaccess file and it'll ignore all the things you want it to and process the ones you want it to.

All together now:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f [NC,OR]
RewriteCond %{REQUEST_FILENAME} -d [NC]
RewriteRule .* - [L]
RewriteRule ^([A-Za-z0-9-]+)$ index.php?req=$1 [L]

I just thought I should share this little tidbit for anyone else that might be frustrated by this harmless yet annoying little problem.

By the way, here is a fantastic mod_rewrite reference (PDF) [http://www.ilovejackdaniels.com/mod_rewrite_cheat_sheet.pdf] for anyone that might need one.