【问题标题】:How to block direct access to my custom 404 page in Apache? [closed]如何阻止直接访问我在 Apache 中的自定义 404 页面? [关闭]
【发布时间】:2020-12-28 02:20:17
【问题描述】:

我在 Ubuntu 中使用 Apache2 作为 Web 服务器,我的根目录是 /var/www/html。在那里我有一个 .htaccess 文件与

RewriteEngine on
ErrorDocument 404 /custom404.html

在里面。这行得通。当我访问 mydomain.com/arandomstring 时,我看到了 custom404.html 页面。但是,我想要做的是阻止对 custom404.html 的直接访问,例如 domain.com/custom404.html 应该不起作用。我将如何实现这一目标?我对 StackOverflow 进行了广泛的搜索,但在这方面没有找到任何帮助。

【问题讨论】:

标签: linux apache .htaccess ubuntu http-status-code-404


【解决方案1】:

您不能简单地阻止所有访问,因为自定义错误文档需要可访问才能被提供。

但是,您可以通过检查 REDIRECT_STATUS 环境变量来阻止直接访问,该变量在初始请求时为空,并在发生错误时设置为 HTTP 状态代码(例如,在 404 的情况下为“404”未找到)。

例如在.htaccess中使用mod_rewrite:

RewriteEngine On

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^custom404\.html$ - [F]

当直接请求 /custom404.html 时,这将提供 403 Forbidden。或者将 F 更改为 R=404 以提供 404 Not Found(不触发重写循环)。

更新:如果在 server(或 virtualhost)上下文中使用,那么您需要在 RewriteRule 上添加斜杠前缀 模式。例如:RewriteRule ^/custom404\.html$ - [F]

    <Location /custom404.html>
       RewriteEngine On
       RewriteCond %{ENV:REDIRECT_STATUS} =""
       RewriteRule .* - [R=404]
    </Location>

这样写(下面的代码)会更简单(并且效率略高)(不需要&lt;Location&gt; 包装器):

RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} =""
RewriteRule ^/custom404\.html$ - [R=404]

【讨论】:

  • 嗨+MrWhite,非常感谢。然而,我放弃了我的 .htaccess 文件,而是将 ErrorDocument 404 /custom404.html 放在了我的 000-default.conf 文件中。下面我把 RewriteEngine On RewriteCond %{ENV:REDIRECT_STATUS} ="" RewriteRule .* - [F] 。这和你写的一样吗?
  • 基本上是一样的。但是,&lt;Location&gt; 包装器是多余的(.* 正则表达式也是如此)- URL 检查可以直接在 RewriteRule 指令中执行-如我的回答所示。这样会更有效率。但请注意,如果指令直接在服务器配置中(在 directory 上下文之外),那么您需要在 RewriteRule pattern 上添加斜杠前缀。例如。 RewriteRule ^/custom404\.html$ - [F].
  • 我认为pastebin.com/uyGK9rN2 可能会帮助您查看我的 .conf 文件。这个对吗?特别是第 9 行 onwords -- .... +MrWhite
  • 我已经更新了针对您的代码的答案。
  • “我不明白你的更新是什么意思。” - 我是说像我在回答中所做的那样编写它会更简单。就像我在回答中所说的那样,&lt;Location&gt; 包装器不是必需的。
猜你喜欢
  • 2017-09-02
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多