1. Home
  2. How To
  3. How to Specify Error Pages (Such as 404) Using .htaccess

How to Specify Error Pages (Such as 404) Using .htaccess

Introduction

Considering the usability and design aspects of your website, it is a good practice to include custom error pages for the possible errors like a “404 not found”. This will make your website more user friendly and provide an option for the user as well as the website owner to redirect the request to another resources that may be interesting to the visitor. Most of the web visitors will not care to return back to the main website or other resources in the website after encountering an unfriendly/default error response from the web server. If a script crashes and produces a “500 Server Error” response, then this response can be replaced with either some friendlier text or by a redirection to another URL (local or external).

Creating Custom Error Pages

Use SSH to connect to your server and navigate to the website document root location. Use your favourite text editor to create an error page named 404.html with the sample contents as shown below.

<html>
<head>
<title> Custom 404 Error Page</title>
</head>
<body>
<p> The resource you tried is currently unavailable in server, please navigate back and try other products.</p>
</body>
</html>

Assign proper permission for the file,

chmod  644 404.html</span>
chown user.user 404.html

Configuring Web Server to Use Custom Error Page

Apache webserver can be configured to use custom error pages and the declaration for the same is by using the directive “ErrorDocument”. The syntax is as shown below.

ErrorDocument error-code  [path to error document]

A sample declaration is as noted below for a 404 error page considering you have the error document as 404.html placed in you website document root.

ErrorDocument 404 /404.html</span>

The error document directive can be added to the virtualhost section of your website.

Open the httpd.conf using a text editor, find the virtual host section of your website.

<VirtualHost *:80>

ServerName mydomain.com

…..

….

..

.

ErrorDocument 404.html

</VirtualHost>

Test Apache configuration and reload it to make the error document in effect.

Updated on May 31, 2019

Was this article helpful?

Related Articles