【问题标题】:How to display Apache's default 404 page in PHP如何在 PHP 中显示 Apache 的默认 404 页面
【发布时间】:2011-05-10 16:14:17
【问题描述】:

我有一个需要处理 URI 以查找页面是否存在于数据库中的 web 应用程序。使用 .htaccess 将 URI 定向到应用程序没有问题:

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ index.php?p=$1 [NC]

我的问题是,如果页面不存在,我不想使用用 PHP 编写的自定义 404 处理程序,我想显示默认的 Apache 404 页面。当 PHP 确定页面不存在时,有什么方法可以让 PHP 将执行交给 Apache?

【问题讨论】:

标签: php apache .htaccess http-status-code-404


【解决方案1】:

我认为您不能将其“交还”给 Apache,但您可以发送适当的 HTTP 标头,然后像这样显式包含您的 404 文件:

if (! $exists) {
    header("HTTP/1.0 404 Not Found");
    include_once("404.php");
    exit;
}

更新

PHP 5.4 引入了http_response_code 函数,这使得它更容易记住。

if (! $exists) {
    http_response_code(404);
    include_once("404.php");
    exit;
}

【讨论】:

    【解决方案2】:

    对于上述情况,我知道的唯一可能的方法是在您的index.php 中使用这种类型的 php 代码:

    <?php
    if (pageNotInDatabase) {
       header('Location: ' . $_SERVER["REQUEST_URI"] . '?notFound=1');
       exit;
    }
    

    然后像这样稍微修改您的 .htaccess:

    Options +FollowSymlinks -MultiViews
    RewriteEngine on
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteCond %{QUERY_STRING} !notFound=1 [NC]
    RewriteRule ^(.*)$ index.php?p=$1 [NC,L,QSA]
    

    这样,Apache 将在这种特殊情况下显示默认的 404 页面,因为从 php 代码中添加了额外的查询参数?notFound=1,并且在 .htaccess 页面中对相同的查询参数进行了否定检查,下次它不会被转发到 index.php .

    PS:/foo这样的URI,如果在数据库中找不到,在浏览器中会变成/foo?notFound=1

    【讨论】:

    • 如果您从 404 处理程序中调用它,则会循环。
    • header('Location: /non-existent-page-url'); 不应该来自您的自定义 404 处理程序。看我的回答,我在上面写了index.php。事实上,如果你想展示 Apache 的 404 处理程序,你不应该真的有一个自定义的 404 处理程序。我建议先在您的 apache 配置或 .htaccess 中注释掉 ErrorDocument 404
    • 我就是这样做的:我在 .htaccess 中使用了您的建议以及 Marco Demaio 建议的解决方案,该解决方案使用 file_get_contents() 获取页面 /foo?notFound=1 并回显它。不完全是我想要的,但足够接近。
    • @Matt;很高兴它起作用了。但是我认为您只是想显示 Apache 的 默认 404 错误页面,并且没有使用 ErrorDocument 404 的任何自定义 404 页面。如果确实如此,则不需要任何file_get_contents() 类型命令。
    【解决方案3】:

    调用这个函数:

    http_send_status(404);
    

    【讨论】:

    • 这个需要pecl_http包,他可能安装不了
    • 很好的解决方案,但它是共享服务器,没有任何 pecl 包。不过非常感谢。
    猜你喜欢
    • 2017-11-21
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2016-03-02
    • 2012-10-06
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多