为了制作友好的URL,以下是应用的htaccess代码:
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]
这现在适用于:
mydomain.com/pages
到mydomain.com/index.php?id1=pages
mydomain.com/pages/xyz
到mydomain.com/index.php?id1=pages&id2=xyz
另外,当我在URL中手动输入mydomain.com/index.php?id1=pages&id2=xyz
时,它会重定向到mydomain.com
。
现在,当我输入另一个类似的mydomain.com/templates
模板是存在的目录时,它会重定向到mydomain.com/templates/?id1=templates
我尝试添加这些行,但徒劳无功:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1'.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]
我的目录结构:
www/
.htaccess
index.php <--- main router
templates/
img/
css/
...
...
other_directories/
...
...
index.php
应收到 ID1 和 ID2。
如何使用 htaccess 避免这种情况(当存在具有该名称的目录时)?
注意:这里已经问过这个问题了。但是再次发布,因为它没有获得可观的观看次数,也没有回答这个问题!
您应该使用重定向规则在目录前面强制使用尾部斜杠:
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]
注意:从未测试
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]
结果
mydomain.com/pages/= mydomain.com/index.php?id1=1
mydomain.com/pages/xyz = mydomain.com/index.php?id1=pages&id2=xyz
它不会重定向 mydomain.com/templates/和 mydomain.com/another_directory/
如果/templates 是现有的目录,您可以使用 RewriteCond 将其排除
RewriteCond %{REQUEST_URI} !^/templates [NC]
RewriteRule ^([^/'.]+)$ index.php?id1=$1 [NC,L,QSA]
或者,可以在其他规则之前使用以下规则来传递不变的 URI:
RewriteRule ^templates - [L]