klenium
klenium

Reputation: 2617

htaccess - Rewriterule redirects to wrong URL

I have a simple rewrite:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?p=$1 [QSA]

Anything that is not an existing file should be forwarded to index.php. However, there's a directory, images, there are sevenal images in it, but no index.php|html. When I open localhost/images, without a closeing slash (localhost/images/ works fine), it redirects me to localhost/images/?p=images. How should I solve that?

Upvotes: 2

Views: 211

Answers (1)

anubhava
anubhava

Reputation: 786329

That is happening because of the mod_dir module that runs after mod_rewrite adding a trailing slash to directories. You should add a condition to avoid rewriting directories in your rule. Also add a trailing slash using a redirect rule:

RewriteEngine on

# add a trailing slash to directories
RewriteCond %{DOCUMENT_ROOT}/$1 -d
RewriteRule ^(.*?[^/])$ %{REQUEST_URI}/ [L,R=302]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?p=$1 [QSA,L]

Upvotes: 2

Related Questions