我想知道如何使用mod重写将没有尾部斜杠的一级子文件夹重写为php文件。
例如
/test -> rewrites to file.php?id=test
/test/ -> trailing slash so it follows through as normal to /test/
/test/test -> second level sub folder so it follows through as normal to /test/test
/ -> homepage needs to follow through as usual to index.php
我试着想出一条规则,在一行中做到这一点。对于上面的例子,test只是一个例子,规则应该重写任何字符串。
您可以在DOCUMENT_ROOT/.htaccess
文件中使用以下代码:
RewriteEngine On
RewriteBase /
RewriteRule ^([^/.]+)$ file.php?id=$1 [L,QSA]
您只能通过禁用mod_dir的DirectorySlash
来做到这一点。要求在目录上使用尾部斜杠是有充分理由的,因为否则即使有索引文件,也可以查看整个内容。所以这是非常危险的。
DirectorySlash Off
RewriteEngine On
# attempt to add trailing slashes
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^([^/]+)/(.+[^/])$ /$1/$2/ [L,R]
# route to file.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)$ /file.php?id=$1 [L]