PHP - 如何让 php 在 header 404 上显示网络服务器 404 错误页面?

PHP - How can i make php to show webservers 404 error page on header 404?

我正在使用 PHP 编写脚本,有时我需要抛出“404 Not Found”状态消息。我试过这个:

<?php
header($_SERVER['SERVER_PROTOCOL']." 404 Not Found");
header("Location: 404.html");
exit();
?>

但它会将用户重定向到 404.html 页面,我认为这样做不是好的做法。相反,我想让用户保持在他访问的同一页面上,抛出 404 状态代码并显示 404.html 内容。

我也试过在我的重写规则中设置错误页面,它工作正常。但我希望 PHP 显示 404 文件的内容以及 404 状态代码。

我也试过:

<?php
header($_SERVER['SERVER_PROTOCOL']." 404 Not Found");
exit(); 

但这只给出了一个 404 状态代码和一个空白页面。我想获取 404.html 或 404.php 文件的内容。

使用file_get_contents:

header($_SERVER['SERVER_PROTOCOL'].file_get_content("404.html"));
exit(); 

或者直接使用回显:

echo file_get_content("404.html");
exit();

也许使用 apache .htaccess 文件是更好的方法。

.htaccess中:

ErrorDocument 404 /not_found.html

使用 include 包含其中包含 404 错误消息的文件,并将 header 设置为 404。 请确保在输出任何其他内容之前发送 header。

<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
include("404.html");
exit(); // terminate the script
?>