non-existing 动态 URL 的 404 错误处理
404 error handling for a non-existing dynamic URL
现在我正确设置了 .htaccess:
ErrorDocument 404 /404.php
每当我访问像 mysite.com/g.php 这样的 non-existing 页面时,它就会被重定向到 404.php,header 显示 404 状态。
每当有人试图访问不存在的故事时,例如我的网站。com/story/123456 404 状态在 header 中,但不会重定向到 404 页面。
只要故事不存在,我就会使用此代码:
if ($result == 0) { header("HTTP/1.0 404 Not Found"); exit();}
我做错了什么?
这是设置 http 响应状态的正确方法:
<?php
// ...
if ($result == 0) {
http_response_code(404);
exit();
}
在您的 http 服务器主机配置中(或者,如果确实需要,在动态配置文件 (.htaccess
) 中)与 ErrorDocument 404 /404.php
一起应该可以满足您的需求。
对应文档:http://php.net/manual/en/function.http-response-code.php
为您的错误文档提供完整路径:
ErrorDocument 404 http://yourdomain.com/404.php
好的,我找到了问题的解决方案。
此代码会给出 404 错误,然后我包含 404 页面以显示页面:
header("HTTP/1.0 404 Not Found"); include '404include.php'; exit();
现在我正确设置了 .htaccess:
ErrorDocument 404 /404.php
每当我访问像 mysite.com/g.php 这样的 non-existing 页面时,它就会被重定向到 404.php,header 显示 404 状态。
每当有人试图访问不存在的故事时,例如我的网站。com/story/123456 404 状态在 header 中,但不会重定向到 404 页面。
只要故事不存在,我就会使用此代码:
if ($result == 0) { header("HTTP/1.0 404 Not Found"); exit();}
我做错了什么?
这是设置 http 响应状态的正确方法:
<?php
// ...
if ($result == 0) {
http_response_code(404);
exit();
}
在您的 http 服务器主机配置中(或者,如果确实需要,在动态配置文件 (.htaccess
) 中)与 ErrorDocument 404 /404.php
一起应该可以满足您的需求。
对应文档:http://php.net/manual/en/function.http-response-code.php
为您的错误文档提供完整路径:
ErrorDocument 404 http://yourdomain.com/404.php
好的,我找到了问题的解决方案。
此代码会给出 404 错误,然后我包含 404 页面以显示页面:
header("HTTP/1.0 404 Not Found"); include '404include.php'; exit();