如何在 PHP 中显示 Apache 的默认 404 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5953096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:00:48  来源:igfitidea点击:

How to display Apache's default 404 page in PHP

phpapache.htaccesshttp-status-code-404

提问by Matt

I have a webapp that needs to process the URI to find if a page exists in a database. I have no problem directing the URI to the app with .htaccess:

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

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

My problem is that if the page does not exist, I do not want to use a custom 404 handler written in PHP, I would like do show the default Apache 404 page. Is there any way to get PHP to hand execution back to Apache when it has determined that the page does not exist?

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

采纳答案by anubhava

The only possible way I am aware of for the above scenario is to have this type of php code in your index.php:

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

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

And then slightly modify your .htaccess like this:

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

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

That way Apache will show default 404 page for this special case because of extra query parameter ?notFound=1added from php code and with the negative check for the same in .htaccess page it will not be forwarded to index.php next time.

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

PS:A URI like /foo, if not found in database will become /foo?notFound=1in the browser.

PS:像 URI 这样的 URI /foo,如果在数据库中找不到,就会/foo?notFound=1在浏览器中出现。

回答by andrewtweber

I don't think you can "hand it back" to Apache, but you can send the appropriate HTTP header and then explicitly include your 404 file like this:

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

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

Update

更新

PHP 5.4 introduced the http_response_codefunction which makes this a little easier to remember.

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

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

回答by AJ.

Call this function:

调用这个函数:

http_send_status(404);