htaccess redirect fails to redirect when directory exists

孤者浪人 提交于 2019-12-20 03:53:06

问题


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!


回答1:


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] 



回答2:


Note: Never Tested

RewriteEngine On

# If the director's are static     
# Redirect exclude for templates, also can add the aonther directory's
RewriteRule ^(templates|another_directory)($|/) - [L]    

# Redirect General
RewriteRule ^([a-zA-Z0-9-/]+)/([a-zA-Z0-9-/]+)$ index.php?id1=$1&id2=$2 [L]
RewriteRule ^([a-zA-Z0-9-/]+)/([a-zA-Z0-9-/]+)/ index.php?id1=$1&id2=$2 [L]
RewriteRule ^([a-zA-Z0-9-/]+)/$ index.php?id1=$1 [L]

Result

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

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

It wont redirect for mydomain.com/templates/ and mydomain.com/another_directory/




回答3:


If /templates is an existent dir, you can exclude it using a RewriteCond

RewriteCond %{REQUEST_URI} !^/templates [NC]
RewriteRule    ^([^/\.]+)$    index.php?id1=$1    [NC,L,QSA]

or you can use the following rule before your other rules to pass the uri unchanged:

RewriteRule ^templates - [L]  


来源:https://stackoverflow.com/questions/36856004/htaccess-redirect-fails-to-redirect-when-directory-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!