Home » How to create a custom 404 error page for website using htaccess

How to create a custom 404 error page for website using htaccess

Last Updated on June 8, 2021 by Amit

In this article I will show how you can create a custom Error page for your website . A custom error page is the one that is shown to your site visitors when they type a broken URL.
If you don’t want to show the dedicated error page then you can create your own page . With the step by step instructions , I will explain how you can easily set up your custom error page with the help of your htaccess file.

First create an error.php file in your web directory

First of all, you need to create a new file that will be served to visitors upon requesting a broken link.

Create a new file named 404-error.php . The file name is just an example here you can change it to whatever name you like.
Add your custom html to the web page . The example error text code is shown below :

Error 404

Sorry, the page you requested couldn't be found.

Save the file in your root web directory and go to the next step which is mentioned below.

Edit your htaccess file to add the custom error code

You will need to add a one single block of code to your htaccess to set up the custom error page redirection.
At the top of your htaccess file, put the following block of code :

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /404-error.php [L]

Make sure the rule is at the top or before other directives in your htaccess.
Don’t try to add this to your WordPress site. The solution won’t work with WordPress.

The code above checks the requested URL path if it doesn’t exist then the request is silently forwarded to the error page. This doesn’t change the URL but makes the internal redirection instead so when your visitors will request a broken link they will see the contents from the custom error file.

If you want to redirection to be visible to client , you can just and a [R] redirect flag to the rule.
Just modify the rule line like the following :

RewriteRule ^ /404-error.php [L,R]

Leave a Reply

Your email address will not be published. Required fields are marked *