How to create custom 401, 403 and 500 error pages?

person shubham sharmafolder_openhtaccesslocal_offeraccess_time February 3, 2017

EError pages are served up via .HTACCESS, if you are using Apache you would use the ErrorDocument directive and add the status and URL to it.

So it would look like this in your .htaccess file:

 

You could use the following function below. This will dynamically add what is needed to the HTACCESS file for you or you could manually do it.

1. Add Pages:

You would then need to go into your Dashboard and create the Pages like any normal page (‘Dashboard’ > ‘Pages’ > ‘New’). They can be titled what ever you wish, just make sure the slug is the same as in the function below (Slug: error-401, error-403, error-404, error-500). Also you can use page template to create whatever layout and style you want for these specific pages. Follow WordPress Codex instructions for this.

2. Add Function:

 

NB!! NOTES ON THE ABOVE FUNCTION

When moving your website or changing URL structure

The thing to remember with the above function is although it will check to see if the ErrorDocument directives already exist before writing them to your HTACCESS file it will not rewrite the ErrorDocument directives should you change or move your blog to reflect the updated page locations. You would need to delete the existing ErrorDocument directives in your HTACCESS file first and then rerun this function to create the new directives.

Correct Hook to fire the function ONLY ONCE

The other thing to note is this function, using the init action will run every time your pages load which is super unnecessary and wasteful so I would suggest adding it to a plugin and using the register_activation_hook rather so it only fires once on plugin activation

File Permissions

Also it is imperative that your .htaccess is writable when using the above function, so make sure it has the correct file permissions, something like CHMOD777.

warningComments are closed.