【发布时间】:2014-02-04 12:29:03
【问题描述】:
我正在尝试配置一个 .htaccess 文件以将所有 url 重新路由到最近的索引子目录,如下所示:
http://example.com/admin/blah/test/whatever 应该留在地址栏中,但指向:
- http://example.com/admin/blah/test/whatever/index.php如果存在,否则:
- http://example.com/admin/blah/test/index.php如果存在,否则:
- http://example.com/admin/blah/index.php如果存在,否则:
- http://example.com/admin/index.php
如果 url 是一个实际文件的 URL,它应该总是转到那个文件。所以 http://example.com/admin/blah/file.css 或 http://example.com/admin/blah/item.inc 如果存在,它们应该仍然可以工作,否则它应该重定向到该文件夹中的 index.php 或最近的父文件夹,如上所示。
如果可能的话,我还想让它只影响一个子文件夹。在上面的示例中,我假设 .htaccess 文件将位于 /admin/ 文件夹中。
更新: 以下是目前有效的方法:
# No Directory Listings or trailing slashes
Options -Multiviews -Indexes +FollowSymLinks
<IfModule mod_rewrite.c>
RewriteEngine On
DirectorySlash Off
# See if the current request is a directory containing an index file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}/index.php -f
RewriteRule ^(.*)/?$ $1/index.php [L,QSA]
# if index.php doesn't exist in current dir then
# forward to the parent directory of current REQUEST_URI
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1$2/index.php !-f
RewriteRule ^(.*?/)?([^/]+)/?$ $1 [L,QSA]
</IfModule>
这主要是有效的。如果我输入 http://example.com/admin?p=2 它会按预期解析,但如果我使用 URL http://example.com/admin/?p=2 它也会解析,而无需显式删除尾部斜杠。
【问题讨论】:
-
如果您想要特定于子文件夹的规则,请将 .htaccess 文件放在子文件夹中。
标签: php apache .htaccess mod-rewrite