为什么http_response_code()不起作用?

时间:2014-12-20 15:11:33

标签: php header

我在PHP 5.4.35上。

此代码:

<?php
http_response_code(404);
header('Location: /');
?>

让我的服务器返回这个答案:

HTTP/1.1 302 Moved Temporarily
Date: Sat, 20 Dec 2014 15:06:32 GMT
Server: Apache
X-Powered-By: PHP/5.4.35
Location: /
Content-Length: 0
Keep-Alive: timeout=2, max=200
Connection: Keep-Alive
Content-Type: text/html

为什么我看不到404


修改

根据答案,Location - 标头会覆盖404状态代码。由于被调用的页面暂时没有移动但从未存在,我现在提供301 Moved Permanently状态代码http_response_code(301),该代码与Location - 标题一起使用。

2 个答案:

答案 0 :(得分:1)

根据文档,如果您向下发送位置标题,如果它不是201或3xx状态代码,则会产生302.

http://php.net/manual/en/function.header.php

答案 1 :(得分:1)

您正在发送一个Location标头,用404 Not Found标头覆盖302 Found/Moved Temporarily

无论如何,重定向用户而不是显示404都没有意义。我建议您发送404错误代码,以便搜索引擎知道该页面不再存在(并删除重定向)。

并显示一个可点击的链接返回主页(并显示一个网站搜索框),以便错误页面仍可供人类访问者使用。

相关问题