How do I return the correct HTTP status code for my 404 error page?

de_DEes_ESfr_FRit_IT

A 404 error page is basically a HTML document which you can design any way you like.

Source code: HTML markup of a 404 error page

Source code: HTML markup of a 404 error page

With a self-designed error page, you have to make sure that the correct HTTP status code is returned. In our example, the HTTP Status Code is “404”.

We return the desired HTTP Status Code with the help of the following PHP code:

<?php
header("HTTP/1.0 404 Not Found");
?>

If your PHP is not executed as an Apache module on your webserver but as FastCGI, the “HTTP/1.0” part in the PHP code has to be replaced by “Status:”.

We therefore add these three lines of PHP code to the very top of the HTML markup in the document:

Source code: HTML markup of a 404 error page with the HTTP status code

Source code: HTML markup of a 404 error page with the HTTP status code

To make sure that the PHP code is interpreted correctly, we change the file ending from .html to .php. This makes the document a classic PHP document, in the eyes of the webserver.

As our final step, we have to reference the location of our 404 document in the .htaccess file.

We add the following to an empty line of the .htaccess file:

ErrorDocument 404 /directory/404.php

If there is no .htaccess file within in the root directory of the webhost yet, it can be easily created.

Related posts