htaccess redirect when directory exists

时间:2016-04-25 08:55:32

标签: apache .htaccess mod-rewrite

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

Edit 1:

I tried adding this line but in vain:

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

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

1 个答案:

答案 0 :(得分:1)

RewriteEngine On

RewriteCond %{THE_REQUEST} /.+?\.php[\s?] [NC]
RewriteRule ^ - [F]
#serve dirs without rewriting
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]    
#####
RewriteRule    ^([^/\.]+)$    index.php?id1=$1    [NC,L,QSA]  
RewriteRule    ^([^/\.]+)/([^/\.]+)$    index.php?id1=$1&id2=$2    [NC,L,QSA]