By using this site you agree to the use of cookies.

Learn more

Share via:

Creating Your Own Custom Error Pages

How to create your own custom error pages using htaccess or PHP.

Edited: 2017-06-15 15:30

To create your own custom error pages, you will need to either link them from your server configuration files, or use a server-sided scripting language such as PHP to display the error.

Typically a CMS will handle errors related to content managed by the CMS, but files outside might just get the standard browser error page. This can be avoided by creating a custom error page for static content.

Using a Static HTML Page

You can use a static HTML page, which simply shows a standard 404 message – and that would be fine in a lot of cases – but sometimes it may be preferred to show a little more than the same error on all 404 errors. The below is an example of a static error page:

<!DOCTYPE html>
<html lang="en-US">

 <head>
   <title>404 Not Found</title>
   <meta name="robots" content="noindex,nofollow">
   <style type="text/css">
   </style>
 </head>

 <body>
  <h1>404 Not Found</h1>
  <p>Nothing was found on the specified location.</p>
 </body>
</html>

A static page should be linked to from the server configuration files or from a .htaccess file in the website root.

ErrorDocument 404 /errors/my-404-page.html

The above declaration links to a generic error page placed in the /errors/ directory, you would place all generic errors in this directory.

Using a Dynamic PHP Page

Using PHP allows us to include additional information, such as the exact URL requested by the user. We should however replace special characters with HTML alternatives – to avoid security problems – this can be done using the PHP htmlentities function.

<?php
header("HTTP/1.0 404 Not Found");
?>
<!DOCTYPE html>
<html lang="en-US">

 <head>
   <title>404 Not Found</title>
   <meta name="robots" content="noindex,nofollow">
   <style type="text/css">
   </style>
 </head>

 <body>
  <h1>404 Not Found</h1>
  <p>Nothing was found on the specified location:</p>
  <p><?php echo htmlentities($_SERVER['REQUEST_URI']); ?></p><p><a href="/">Frontpage</a></p>
 </body>
</html>

It can sometimes be a good idea to have an error page listed in the server configuration, as this will handle errors related to URLs not handled by your CMS, such as static images or video files.