htaccess ErrorDocument 404 redirect not working

2019-05-30 07:46发布

问题:

Please tell me why this is not working. It was working but has inexplicably decided to stop working. In php I issue a 404 if the page is not found like so.

if(checkPageExists($escaped_url_page_name)){
header('HTTP/1.1: 200 OK');
}else{
header("HTTP/1.0 404 Not Found");
die;
}

My htaccess is

php_flag magic_quotes_gpc Off

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]

ErrorDocument 404 /404.php

The 404 page is on the root and is name 404.php. Why would that not work when five minutes ago it was and nothing has changed. I have tested the page with fiddler and it is indeed throwing the 404's but the redirect is not happening. I have friendly urls implemented, but I would not think this affects it as the "/" in the htaccess refers to the physical root of the site I thought. Thanks in advance.

回答1:

I had a similar issue once - when PHP throws a 404 header, Apache generally won't make a 404 page for it. (Edit: It probably has to do with whether PHP outputs any text. I haven't really experimented with it much.) If you check the headers in your browser, you can see that the 404 header worked, even if the page is blank.

I'm not sure about an automated solution, but I just made an http_error($code) function that prints my custom error page and called that along with header() whenever my code manually triggered a 404. Then I bound a bit of code to ErrorDocument that calls http_error only:

ErrorDocument 404 index.php?http_error=404
ErrorDocument 403 index.php?http_error=403

...and so on.