Forum Moderators: phranque

Message Too Old, No Replies

Make rewrites only rewrite if the directory doesn't already exist

         

fmchris

9:43 pm on Jul 30, 2008 (gmt 0)

10+ Year Member



Alright, I'm fairly new to mod_rewrite, and fairly new to RegEx. I have my directory set up like this:

img/
.htaccess
image.php
index.html

Now, I have the following in my HTACCESS file:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([a-z0-9_-]+)/?([a-z0-9_-]+)?/?$ image.php?user=$1&template=$2 [NC,L]

This will rewrite any combination of the following:

/sample/test
/sample/test/
/sample
/sample/

To image.php?user=sample$template=test (unless you don't include test). Which is exactly what I need. However, if I attempt to go to

[sample.com...]

it will redirect me to image.php?user=img

How do I keep it from redirecting ACTUAL directories?

fmchris

10:08 pm on Jul 30, 2008 (gmt 0)

10+ Year Member



Nevermind, I've fixed my own problem. If, in the future, anyone needs the solution:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^([a-z0-9_-]+)/?([a-z0-9_-]+)?/?$ image.php?user=$1&template=$2 [NC,L]

Unless there's some way of making this more efficient.

jdMorgan

9:27 pm on Aug 1, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Don't use the "-l" check unless you know for a fact that you use symbolically-linked files.

Make the RewriteRule pattern as specific as possible, so that the CPU-intensive "exists" checks only run when absolutely required (RewriteConds are only processed if the RewriteRule pattern matches). These checks must call the file system, and depending on caching, may invoke a physical disk read, so avoid them at all costs, especially on busy and/or shared servers.

Jim

fmchris

9:42 pm on Aug 1, 2008 (gmt 0)

10+ Year Member



The RewriteRule is as specific as I can see making it, since it has to process variable user and template names so the PHP renders properly. I would add length checks, but I don't want the script to 404 if the length is incorrect, that is all handled by the PHP.

Thanks for the heads-up about -l, I'll remove that. I have never used file checks before, so I went ahead and used all three "just in case".