Thamizhan Thamizhan - 7 months ago 20
PHP Question

htaccess redirect fails to redirect when directory exists

For making friendly URLs, Following is the htaccess code applied:

RewriteEngine On

RewriteCond %{THE_REQUEST} /.+?\.php[\s?] [NC]
RewriteRule ^ - [F]

RewriteRule ^([^/\.]+)$ index.php?id1=$1 [NC,L,QSA]
RewriteRule ^([^/\.]+)/([^/\.]+)$ index.php?id1=$1&id2=$2 [NC,L,QSA]


This now works for:


  1. mydomain.com/pages
    to
    mydomain.com/index.php?id1=pages

  2. mydomain.com/pages/xyz
    to
    mydomain.com/index.php?id1=pages&id2=xyz



also, when I enter
mydomain.com/index.php?id1=pages&id2=xyz
manually in the URL, it redirects to
mydomain.com
.

Now, when I enter another like
mydomain.com/templates
where templates is a directory that exists, it redirects to
mydomain.com/templates/?id1=templates


I tried adding these lines but in vain:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]


My directory structure:

www/
.htaccess
index.php <--- main router
templates/
img/
css/
...
...
other_directories/
...
...


index.php
should receive id1 and id2.

How shall I avoid this condition (when directory with that name exists) using htaccess?

Note: This question is already asked here. But posting again, as it didn't gain considerable views nor answered the issue!

Answer

You should force a trailing slash in front of directories using a redirect rule:

RewriteEngine On

RewriteCond %{THE_REQUEST} /.+?\.php[\s?] [NC]
RewriteRule ^ - [F]

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

RewriteRule ^([^/.]+)/?$ index.php?id1=$1 [L,QSA]

RewriteRule ^([^/.]+)/([^/.]+)/?$ index.php?id1=$1&id2=$2 [L,QSA] 
Comments