简体   繁体   中英

PHP 404 response header

I use .htaccess RewriteRules to pass the url to index.php. If the specified page name isn't found in the database, I want my script to throw proper 404 responses.

The way I have tried to achieve this is:

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

Analysing the HTTP responses in my browser, the response comes back fine:

HTTP/1.1 404 Not Found 

However, I would like to be able to output a friendly 404 page, but anything after the header() function gets disregarded, and anything before ... well ... that'd be stupid.

Can anyone suggest how to output a 404 error message from the script?

Thanks.

You have to make sure the output (or ErrorDocument) is larger than 512 bytes as to make sure Internet Explorer doesn't display it's own error-page. This is probably why you have experienced any output after the header doesn't get displayed.

<?php
header("HTTP/1.0 404 Not Found");
    echo "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL " . $_SERVER['REQUEST_URI'] . " was not found on this server.</p>
<hr>
<address>Apache/2.2.3 (CentOS) Server at " . $_SERVER['SERVER_NAME'] . " Port 80</address>
</body></html>";
    exit();
?>

So following (in .htaccess)

ErrorDocument 404 /errordoc.html

is not working for you ?

EDIT: As you see, you can easy throw 404 in PHP and then catch it in .htaccess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM