Htaccess error document

Using htaccess you can create custom error pages.

For example, if a page is not found on the server, it shows a simple “404 Page not found” error by browsers. This error page is dull and does not provide any useful information to visitors.

Htaccess allows you to set your own error page with more information or any useful instruction for the user if found “404 page not found” error. You can create a .htaccess file on website root and set your custom file for different errors.

Example: ErrorDocument 404 /error.html

In this .htaccess example, if a file/page is not found (404 error), server will load ‘error.html’ from website root folder.

Different types of Error documents:

There are different types of errors such as ‘401 Unauthorised’, ‘403 Forbidden’, ‘404 file not found’, and ‘500 Internal Server’ that .htaccess can handle.

ErrorDocument 401 /401.html
ErrorDocument 403 /error.html
ErrorDocument 404 /404.html
ErrorDocument 500 /error.php

You can change the file name and file location according to your requirement.

htaccess custom error message

It is possible to directly put the custom error message instead of providing an error document path. Did you know that even HTML can be used directly in the message?

ErrorDocument 401 "Sorry, Some error happend"
ErrorDocument 404 "<html><body bgcolor=#ffffff><h1> You got 404 buddy </h1> </body> </html>"

Common Issues & Misconceptions:

Custom 500 error page not working with PHP errors?

If 500 error is triggered by PHP (See example below), it can not be handled by Apache or its the custom error page.

header("HTTP/1.0 500 Internal Server Error");
die();

Important Points: 

  • Once control has been passed to the PHP, it can not go back to Apache for error handling.
  • You can set custom message/page for most errors, but there are certain circumstances where the internal messages are used even if the error page is set using ErrorDocument.

More details along with “How to simulate a 500 error in Apache” is mentioned in this stack overflow thread.


How to set Custom Error page with PHP?


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.