我怎样才能在PHP中创build一个错误404?

我的.htaccess将所有请求redirect到/word_here/page.php?name=word_here 。 PHP脚本然后检查请求的页面是否在它的页面数组中。

如果不是,我怎样才能模拟一个错误404? 我试过这个,但没有奏效:

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

我是否认为redirect到我的错误404页是错误的?

在PHP中生成404页面的最新答案(从PHP 5.4开始)是使用http_response_code

 <?php http_response_code(404); include('my_404.php'); // provide your own HTML for the error page die(); 

die()并不是绝对必要的,但它确保你不会继续正常的执行。

你正在做什么将工作,浏览器将收到404代码。 它不会做的是显示您可能期待的“找不到”页面,例如:

未find

在此服务器上未find请求的URL /test.php。

这是因为当PHP返回一个404代码(至lessApache没有)时,web服务器不会发送那个页面。 PHP负责发送所有自己的输出。 所以如果你想要一个类似的页面,你必须自己发送HTML,例如:

 <?php header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404); include("notFound.php"); ?> 

您可以将Apacheconfiguration为使用相同的页面作为自己的404消息,方法是将其置于httpd.conf中:

 ErrorDocument 404 /notFound.php 

尝试这个:

 <?php header("HTTP/1.0 404 Not Found"); ?> 

通过.htaccess文件创build自定义错误页面

1. 404 – 页面未find

  RewriteEngine On ErrorDocument 404 /404.html 

2. 500 – 内部服务器错误

 RewriteEngine On ErrorDocument 500 /500.html 

3.403 – 禁止

 RewriteEngine On ErrorDocument 403 /403.html 

400 – 不好的要求

 RewriteEngine On ErrorDocument 400 /400.html 

5. 401 – 需要授权

 RewriteEngine On ErrorDocument 401 /401.html 

您也可以将所有错误redirect到单个页面。 喜欢

 RewriteEngine On ErrorDocument 404 /404.html ErrorDocument 500 /404.html ErrorDocument 403 /404.html ErrorDocument 400 /404.html ErrorDocument 401 /401.html 

你是否记得在发送头文件后死()? 404头不会自动停止处理,所以如果有进一步的处理发生,可能看起来没有做任何事情。

对您的404页面进行REDIRECT并不好,但是您可以从中包含没有任何问题的内容。 这样,你有一个页面可以正确的从正确的URL发送一个404状态,但是它也有你的“你在找什么? 页面为人类的读者。