PHP: Can't change 404 status code, but there i

2019-06-07 13:00发布

问题:

I'm processing unavaliable pages in my custom PHP website. To do this I created a .htaccess file with this single line:

ErrorDocument 404 /index.php

At the beginning of index.php I placed this code:

header($_SERVER['SERVER_PROTOCOL'].' 200 OK', true, 200);

This works perfect in my WAMP environment. I'm checking http headers, and it throws:

Status=OK - 200

But in my Linux hosting I always get:

Status=Not Found - 404

And the weird part is that PHP isn't throwing any error at all... it's like something is overriding my headers.

I need to change the status code header, otherwise IE7 and IE8 won't process my result page. Other browsers can deal with this.

Maybe I need something in .htaccess or php.ini, but haven't found anything related. Or, if you know any other method to redirect a 404 and return 200, let me know.

回答1:

A better method of rewriting non existent pages to a PHP file is this:

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule (.*) index.php

This uses mod_rewrite to change anything that is not a directory and not a file to your PHP script. Just remember that if your PHP script recieves a request for something that isn't there, it should send a 404 header.



回答2:

Depending of the configuration of your Webserver, fast-cgi could be enabled. You need an alternate syntax then (as found in PHP documentation):

header("Status: 200 OK"); // for fast cgi
header($_SERVER['SERVER_PROTOCOL'] . " 200 OK");