Michael Samuel
Michael Samuel

Reputation: 3920

Display 404 document from htaccess after sending 404 header in PHP

In PHP I use the following code to indicate page not found:

header("HTTP/1.0 404 Not Found");exit();

In .htaccess file I have the following line to handle 404 custom document:

ErrorDocument 404 /404.html

Now when I send the PHP 404 header I expect it to show the custom 404.html defined in .htaccess but instead it shows a message "this link appears to be broken". So it doesn't show the custom 404 page and if I remove the line from .htaccess it still won't display the regular 404 page of the server and shows also the broken link message.

So how to make it show the 404 page when I send the header in PHP?

Upvotes: 1

Views: 1164

Answers (2)

Jon Lin
Jon Lin

Reputation: 143966

The problem here is that the custom error document denoted by ErrorDocument isn't processed unless the URL processing pipeline can't find a file (or a handler) that the URL points to. In you case, the processing pipeline does find a file, your php file, thus it never reaches a 404 on its own so the ErrorDocument is never applied.

When apache uses the php handler to run your php file, and your php file decides to return a 404, you not only need to provide the 404 response code, but the HTML error document as well. You don't see the default apache error document because apache never thinks the request is a 404 (it handed the request off to your php file). So you need to do something like this:

header("HTTP/1.0 404 Not Found");
include('404.html');
exit();

Upvotes: 6

Alex Ruhl
Alex Ruhl

Reputation: 457

you just send a 404 code to your browser try to redirect to your error 404 page

header('location: http://youdomain.com/404.html'); exit;

Upvotes: 0

Related Questions