Skip to content

How to Return 404 Not Found Just Looks Like Apache's

Sometimes, you may want to prevent specific users from accessing data in some conditions and return them a mild refusal 404 Not Found page instead, just looks like Apache httpd does. For example, you can do this in PHP:

<?php
...
if (isRegistered()) {
  $dump = <<<_END
<!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>{$_SERVER['SERVER_SOFTWARE']} Server at {$_SERVER['SERVER_NAME']} Port {$_SERVER['SERVER_PORT']}</address>
</body></html>
_END;

  header($_SERVER['SERVER_PROTOCOL'] . " 404 Not Found", true, 404);
  exit($dump);
} else {
  //Continue to proceed
}
?>

In the example, I want to refuse the users who have not registered for the service by returning them a 404 Not Found page instead. So first of all, PHP organizes a message for dumping, and then use header() to notify Apache a 404 condition has occurred, and the last, PHP exits with the dumping message.

Leave a Reply

Your email address will not be published.