【问题标题】:Custom 404 for selected URL without ErrorDocument没有 ErrorDocument 的选定 URL 的自定义 404
【发布时间】:2022-01-11 01:19:31
【问题描述】:

我正在尝试为可能存在或不存在的文档或文件夹或文件或链接显示自定义 404 页面,但我仍想出于某种目的向访问者显示 404 消息。

我检查了Setting a custom 404 page for a specific URL in htaccessSetting a custom 404 page for a specific URL in htaccess

代码:

RewriteRule ^foo.html$ /spoof404.txt [L,R=404,NC]
RewriteRule ^hello$ /spoof404.txt [L,R=404,NC]
RewriteRule ^file/example.php$ /spoof404.txt [L,R=404,NC]

使用这些代码,我成功获得了404 Status in header,但它没有显示spoof404.txt 的内容

注意:

  1. 我不是在寻找像 404 或 403 这样的错误文档
  2. 我不是在寻找重定向
  3. 这不是重复的问题。在问这里之前,我已经搜索了 stackoverflow 的其他部分。

【问题讨论】:

    标签: apache .htaccess mod-rewrite url-rewriting http-status-code-404


    【解决方案1】:

    我不是在寻找像 404 或 403 这样的 Errordocument

    为什么不呢?这正是你这样做的方式。仅 Apache(不使用其他服务器端脚本)没有其他方法可以触发 404 HTTP 状态并提供自定义响应。

    例如:

    ErrorDocument 404 /spoof404.txt
    
    RewriteRule ^foo\.html$ - [NC,R=404]
    RewriteRule ^hello$ - [NC,R=404]
    RewriteRule ^file/example\.php$ - [NC,R=404]
    

    当您请求 /foo.html 时,它将触发 404 并且将提供 /spoof404.txt

    当指定 3xx 范围之外的状态 ode 时,substituion 字符串将被忽略(因此使用单个 - - 连字符)。在这种情况下,L 标志也是多余的,因为它在指定非 3xx R 代码时是隐含的。


    更新:

    如何使用example.com/something.php?something=tokens&othertoken=token等参数进行拦截

    RewriteRule 指令仅与 URL 路径匹配,要匹配查询字符串(第一个 ? 之后的所有内容),那么您需要一个额外的 条件RewriteCond 指令)和检查QUERY_STRING 服务器变量。

    例如,要匹配那个 准确 URL(尽管不区分大小写)并触发 404:

    RewriteCond %{QUERY_STRING} ^something=tokens&othertoken=token$ [NC]
    RewriteRule ^something\.php$ - [NC,R=404]
    

    【讨论】:

    • Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. 我得到的是这个而不是 spoof404.txt 的内容
    • 我对外部站点使用热链接保护?也许它是因此而发生的。我正在使用<FilesMatch ".(txt|ini|psd|log|sh)$"> Order Allow,Deny Deny from all </FilesMatch>
    • 是的,“热链接保护”会阻止/something.txt子请求。 (顺便说一句,这不是“热链接保护”,它只是阻止对具有任何这些扩展名的文件的任何请求 - 包括来自您自己的站点。)但是该代码在哪里?它不在您发布的.htaccess 代码中。 (OrderDeny 是 Apache 2.2 指令,以前在 Apache 2.4 上已弃用。如果您使用的是 Apache 2.4,那么您应该改用 Require all denied。)
    • 不,不是那样的。 RewriteRule 指令仅与 URL 路径匹配,您还需要使用 conditionRewriteCond 指令)。我已经更新了我的答案。
    • 确保您没有看到缓存响应。我的回答中的指令只会阻止example.com/something.php?something=tokens&othertoken=token,它不会仅阻止example.com/something.php。 (假设 /something.php 确实存在。)
    猜你喜欢
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 2011-04-06
    • 1970-01-01
    相关资源
    最近更新 更多