htaccess 自定义 403 禁止页面并不总是有效

htaccess Customized 403 Forbidden page not always working

我有一个自定义 403 页面,当我想阻止特定页面时它可以工作,但当我想匹配特定页面时它不起作用 HTTP_REFERER。

使用特定的 HTTP_REFERER 我得到了常规 403,为了测试 HTTP_REFERER 我在另一个站点“mysite.com”上添加了一个 link 到这个项目,当我点击 link 我得到服务器 403 响应:

但我打开我的测试页面“禁止测试”我确实得到了我的自定义 forbidden.php 页面

这是我在 htaccess 中的内容,仅构成以下示例 RewriteRule ^forbidden-test$ - [F] 通过显示我的自定义 403 页面来工作:

Options All -Indexes
# prevent folder listing
IndexIgnore *
RewriteEngine on

RewriteCond %{HTTP_REFERER} \
...  (there are many here)
mysite\.com|\
[L,NC]
RewriteRule .* - [F]
#spam blacklist end

RewriteCond %{HTTP_USER_AGENT} \
12soso|\
192\.comagent|\
1noonbot|\
1on1searchbot|\
3de\_search2|\
3d\_search|\
3g\ bot|\
...  (there are many here)
zyte\
[NC]
RewriteRule .* - [F]
#bad bots end


#Forbidden Test
RewriteRule ^forbidden-test$ - [F]

#ERRORS
RewriteRule ^forbidden/?$ forbidden.php [L,QSA]

ErrorDocument 403 /forbidden

有什么想法吗? 谢谢

注意默认错误消息的实际含义:

Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

对您的自定义错误文档的访问被阻止。内部要求,再次进行所有重写;并且由于原始请求的引荐来源网址(仍然)错误,因此现在禁止访问您的 403 文档

您需要为此引用检查添加一个例外,以便它允许访问您的错误文档。

这里最简单的方法可能是在请求此特定文档时将规则放在最顶部,什么也不做:

RewriteRule ^forbidden\.php$ - [L]

-是一个“非重写”,它什么都不做。 [L] 标志在这里很重要,表示“不要在这一轮处理任何其他规则。”

另外,由于你的错误文档似乎是一个PHP脚本,你应该直接这样定义它,

ErrorDocument 403 /forbidden.php

否则,这需要额外的一轮重写,从 /forbidden 到 /forbidden.php,这真的没有什么好的理由。