如何在自定义错误文档上发送正确的 HTTP 响应


How to send correct HTTP response on custom Error document?

我通过.htaccess配置了我的站点来执行此操作:

ErrorDocument 403 http://www.mydomain.com/error.php?e=403
ErrorDocument 401 http://www.mydomain.com/error.php?e=401
ErrorDocument 400 http://www.mydomain.com/error.php?e=400
ErrorDocument 500 http://www.mydomain.com/error.php?e=500

error.php记录错误并显示用户/客户友好的错误页面。

另外,我还添加了这段代码:

if($_GET['e'] == '404' || $_GET['e'] == '403' || $_GET['e'] == '500' )
{   $error_no = $_GET['e']; } else { $error_no = '200'; }
header(' ', true, $error_code);

因此,当我访问mydomain.com/pagedoesnotexist时,我看到错误页面(但地址栏仍然显示不存在的URL),我收到一个报告,指出触发了404页面,但我查看了我的服务器日志文件,它是这样说的: MY.IP.000.00 - - [date and time] "GET /pagedoesnotexistHTTP/1.1" 200 2450 "-" "USERAGENTINFO"

在我的服务器日志中,我看不到有关 404 的任何内容...... 只有 200...为什么?如何让它发回 404 代码?现在我假设机器人等总是得到 200,这意味着在访问不存在的网站时响应正常......还是我错过了什么?

*题外话:2450代表什么?O_o*

但是请注意,您设置ErrorDocument不正确,这会导致外部重定向并返回200而不是404403等。 按如下方式设置您的ErrorDocument不带域名

ErrorDocument 403 /error.php?e=403
ErrorDocument 401 /error.php?e=401
ErrorDocument 400 /error.php?e=400
ErrorDocument 500 /error.php?e=500

这将在浏览器中保留原始未找到的 URL,同时返回正确的 HTTP 状态代码。

关于您的代码:

您正在设置变量$error_no并在header()函数中使用$error_code。您应该使用:

if($_GET['e'] == '404' || $_GET['e'] == '403' || $_GET['e'] == '500' )
{   $error_no = $_GET['e']; } else { $error_no = '200'; }
header(' ', true, $error_no);