Andelas
Andelas

Reputation: 2052

Limit rewrite rule to exclude a certain directory

When a a rewrite rule to allow us to make friendly URL's with an ID number. The story is only pulled through the ID number, so the text at the end doesn't really matter.

RewriteRule ^news/([0-9]+)$    /news/$1/ [R=301,L]
RewriteRule ^news/([a-zA-Z0-9_-]+)/.*$ /news/story.php?id=$1

Our problem comes when any file linked within /news/images/ , it gets redirected as well. So anything that displays an image from /news/images/ doesn't work.

Can someone help me out? How can we limit the rewrite so that it says "If it's in the /images/ subdirectory, don't rewrite the path"?

Upvotes: 0

Views: 500

Answers (1)

Tim Stone
Tim Stone

Reputation: 19169

You could take the simple route and just avoid the rewrite if the file exists:

RewriteRule ^news/([0-9]+)$    /news/$1/ [R=301,L]

# Ignore the RewriteRule if the request points to a file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond $1 !=tags [NC]
RewriteRule ^news/([a-zA-Z0-9_-]+)/.*$ /news/story.php?id=$1

Alternatively, if you wanted to do the directory checking in case the resource request didn't point to a real file, but should directly generate a 404 response, you can try the following:

RewriteRule ^news/([0-9]+)$    /news/$1/ [R=301,L]

# Check if the path segment after /news/ corresponds to an existing directory
# and if so, don't perform the rewrite
RewriteRule %{DOCUMENT_ROOT}/news/$1/ !-d
RewriteCond $1 !=tags [NC]
RewriteRule ^news/([a-zA-Z0-9_-]+)/.*$ /news/story.php?id=$1

Upvotes: 1

Related Questions