当我使用 php 发送 404 标头时,为什么 apache 不显示 404 错误?
我在代码中的某处有一个 header('HTTP/1.0 404 Not Found');
,但由于某种原因它没有重定向到 Apache 的默认 404 页面。
我在 .htaccess 文件上有一个重写规则,它将每个请求重定向到 index.php。这可能是问题所在吗?
I have a header('HTTP/1.0 404 Not Found');
somewhere along the code but it doesn't redirect to the Apache's default 404 page for some reason.
I have a Rewrite Rule on the .htaccess file that redirects every request to index.php. Could that be the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标头并不是告诉 Apache 显示其 404 页面的内容。相反,当 Apache 显示 404 页面时,它会同时发送 404 标头。标头对浏览器有意义,而不是对服务器有意义。当 Apache 找不到要显示的正确文件时,它会显示 404。由于您处于 PHP 脚本中,Apache 已经找到了它可以显示的文件,因此不会显示自己的 404 页面。
The header is not what tells Apache to display it's 404 page. Rather, when Apache displays its 404 page, it sends a 404 header along with it. The header is meant to have meaning to the browser, not the server. Apache displays a 404 when it can't find the proper file to display. Since you're in a PHP script, Apache has already found a file it can display, and thus won't show its own 404 page.
在这种情况下,PHP 发送的标头仅对浏览器真正重要。 Apache 不会创建自己的页面,因为您已经在处理该页面,如果您发送了某些内容,两者就会发生冲突。
是的,
.htaccess
文件将阻止 Apache 显示错误页面,因为您的规则使 Apache 认为它不再有404
错误,因为它已找到页面来展示。发送标头实际上只是一条“状态消息”,并不会使浏览器或服务器显示特定页面。 (尽管大多数浏览器都会)。
正如 Dav 在评论中指出的那样,您需要将 404 错误发送到他们自己的自定义错误页面。
Headers sent by PHP only matter really to the browser in this case. Apache isn't going to make its own page because you are already processing the page, and if you sent something, the two would conflict.
Yes, the
.htaccess
file is going to stop Apache from showing an error page because your rules makes Apache think it no longer has a404
error, because it has found a page to show.Sending a header is really only a 'status message', and doesn't make the browser or server show a particular page. (Although most browsers will).
As Dav pointed out in the comments, you will want to send 404 errors to their own custom error page.