在/hello/bar中有一个文件foo.php。
所以如果用户说
/hello/bar/foo.php # Access forbidden
/hello/bar/foo # Redirect to foo.php
到目前为止,我所做的是,在/
的.htaccess中,
RewriteEngine on
RewriteRule "^hello/bar/foo$" "hello/bar/foo.php" [L]
RewriteRule "^hello/bar/foo.php$" "-" [F]
但这似乎不起作用。将这两个URL放在一起,服务器会发送一个403错误。我该如何更正?
一旦应用了一组重写规则,结果就会返回给URI解析器,如果URI发生更改,该解析器将重新调用重写规则集(根据新的URI,可以是相同的.htaccess,也可以是不同的.htacccess)。
这意味着,您使用的[L]
标志并没有完全停止重写处理,它只是停止通过规则集处理当前循环。
因此,在.htaccess中,第一条规则将hello/bar/foo
重写为hello/bar/foo.php
,[L]
结束当前重写。URI解析器发现URI已更改,将从顶部重新调用重写。第一条规则这次不适用,但第二条规则会导致Forbidden(又名HTTP 403-Forbidded)。
所以,你需要一种方法来停止这种循环。在Apache的后续版本中,可以使用[end]
标志而不是[L]
。这将彻底结束所有重写。
RewriteEngine on
RewriteRule "^hello/bar/foo$" "hello/bar/foo.php" [END]
RewriteRule "^hello/bar/foo.php$" "-" [F]
请参阅https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_end