Subscribe to PHP Freaks RSS

mod_rewrite and Ignoring Directories

Print
by ober on Jun 12, 2008 2:00:51 PM - 5,710 views

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 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) for anyone that might need one.

Comments

No comments have been posted.

Add Comment

Login or register to post a comment.