apache htaccess在获取没有index.php的目录时不重写URL

guykilcj  于 6个月前  发布在  Apache
关注(0)|答案(2)|浏览(73)

我写了一个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]

字符串
问题是,当我nagivate到'/'没有index.php,它(不希望)显示一个目录列表(或“禁止”,如果索引被禁用).
这是怎么回事?我怎么能让它重写请求到一个没有index.php的目录?

7xzttuei

7xzttuei1#

这几乎是正确的,但在第一个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]

字符串

bqjvbblv

bqjvbblv2#

这得到了一个应该已经起作用的答案,但为了完整起见,我想指出一个替代方案。
如果在导航到的目录中没有index.php,它也应该重写为route.php
你不一定需要使用重写,你可以在你的DirectoryIndex指令中指定这作为一个替代方案:

DirectoryIndex index.php /route.php

字符串
从文件中引用,
可以给出多个URL,在这种情况下,服务器将返回它找到的第一个URL。
因此,它将首先在当前目录中查找index.php,如果不存在,则在根级别查找/route.php

相关问题