Jazzy
Jazzy

Reputation: 6139

mod_rewrite to php file unless directory exists

I have a mod_rewrite rule working to direct non-existing directories to a php file which does a database get based on the $1.

Everything works fine unless the directory does exist, which displays the proper directory, but it also appends the query string when it's not necessary.

I have been scouring the web for the past few hours and trying different methods with no luck.

Does anyone know how to keep this functioning as-is, but get rid of the query string?

Thanks much.

Here is my code:

RewriteEngine On
    Options +FollowSymlinks
    RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^([0-9a-zA-Z\-]+)/$ $1 [R]
RewriteRule ^([0-9a-zA-Z\-]+)$ product.php?product=$1

What ends up happening is the browser displays the URL as http://domain.com/existing_dir/?product=existing_dir

Upvotes: 1

Views: 1208

Answers (2)

Jenny D
Jenny D

Reputation: 1245

Mod_rewrite doesn't affect the query string, it will always be tagged on to the end of the new URL unless you tell mod_rewrite to have an empty query string. This is done by adding just a ? at the end of the new string. So the first line should look like this:

RewriteRule ^([0-9a-zA-Z\-]+)/$ $1? [R]

Upvotes: 0

Jacek Kaniuk
Jacek Kaniuk

Reputation: 5229

try that, it removes / on its own without repeating whole process

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*?)/?$ product.php?product=$1

if You insists on limiting special characters, that would do:

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^([0-9a-zA-Z\-]+?)/?$ product.php?product=$1

+ is 1 or more repeatition, * is 0 or more, and +?, *? are modifiers for not hungry matching - it allows /? to match anything

Additionally in Your example, first RewriteRule is been executed conditionally (when directory does not exists), the second one is executed always (if first whould not break the process) so even if directory exists

Upvotes: 2

Related Questions