我写了一个htaccess文件来重写URL。它应该做什么:当用户访问没有相应 PHP 文件的 URL 时,它会重定向到route.php。
目录的情况有点复杂;如果导航到的目录中没有index.php,则也应该重写为route.php。
这是代码:
RewriteEngine On
# Check if it's a directory without an index.php
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME}/index.php !-f
RewriteRule . route.php [L]
# Check if it's not a file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . route.php [L]
问题是,当我导航到没有index.php的'/'时,它(不必要地)显示目录列表(如果禁用索引,则显示“禁止”)。
发生什么事了?如何让它重写请求到没有index.php的目录?
几乎是正确的,但第一个
RewriteRule
中有一个点,这意味着 URI 中必须至少存在一个字符。然而,对于登陆页面,相对 URI 将只是一个空字符串。
这应该适合你:
RewriteEngine On
# Check if it's a directory without an index.php
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME}/index.php !-f
RewriteRule ^ route.php [L]
# Check if it's not a file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ route.php [L]