PHP 404 响应头

发布于 2024-09-19 08:41:09 字数 398 浏览 11 评论 0原文

我使用 .htaccess RewriteRules 将 url 传递给 index.php。如果在数据库中找不到指定的页面名称,我希望我的脚本抛出正确的 404 响应。

我尝试实现此目的的方法是:

header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");

分析浏览器中的 HTTP 响应,响应返回正常:

HTTP/1.1 404 Not Found 

但是,我希望能够输出友好的 404 页面,但 header() 函数之后的任何内容都会被忽略,以及之前的任何事情……好吧……那是愚蠢的。

谁能建议如何从脚本中输出 404 错误消息?

谢谢。

I use .htaccess RewriteRules to pass the url to index.php. If the specified page name isn't found in the database, I want my script to throw proper 404 responses.

The way I have tried to achieve this is:

header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");

Analysing the HTTP responses in my browser, the response comes back fine:

HTTP/1.1 404 Not Found 

However, I would like to be able to output a friendly 404 page, but anything after the header() function gets disregarded, and anything before ... well ... that'd be stupid.

Can anyone suggest how to output a 404 error message from the script?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

笔落惊风雨 2024-09-26 08:41:10

您必须确保输出(或 ErrorDocument)大于 512 字节,以确保 Internet Explorer 不会显示其自己的错误页面。这可能就是为什么您在标题未显示后遇到任何输出的原因。

You have to make sure the output (or ErrorDocument) is larger than 512 bytes as to make sure Internet Explorer doesn't display it's own error-page. This is probably why you have experienced any output after the header doesn't get displayed.

橪书 2024-09-26 08:41:10
<?php
header("HTTP/1.0 404 Not Found");
    echo "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL " . $_SERVER['REQUEST_URI'] . " was not found on this server.</p>
<hr>
<address>Apache/2.2.3 (CentOS) Server at " . $_SERVER['SERVER_NAME'] . " Port 80</address>
</body></html>";
    exit();
?>
<?php
header("HTTP/1.0 404 Not Found");
    echo "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL " . $_SERVER['REQUEST_URI'] . " was not found on this server.</p>
<hr>
<address>Apache/2.2.3 (CentOS) Server at " . $_SERVER['SERVER_NAME'] . " Port 80</address>
</body></html>";
    exit();
?>
且行且努力 2024-09-26 08:41:10

那么以下(在 .htaccess 中)

ErrorDocument 404 /errordoc.html

对您不起作用?

编辑:如您所见,您可以轻松地在 PHP 中抛出 404,然后在 .htaccess 中捕获它。

So following (in .htaccess)

ErrorDocument 404 /errordoc.html

is not working for you ?

EDIT: As you see, you can easy throw 404 in PHP and then catch it in .htaccess.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文