Apache2 configure custom 404 page not found error page

Written by
Date: 2013-01-11 15:47:35 00:00

Two years ago I have posted about how to set custom 404 "Page not found" error in Nginx. I am working more with Apache than with Nginx these days. After learning about Apache MPM Worker I started with Apache again.

Well today I will show you different ways to configure 404 custom pages with Apache2. For my tests I have used Ubuntu 12.10, but it should work the same on any other distribution.

Custom 404 "Page Not Found" with Apache2

There are different options.

.htaccess file

When you do not have access to the Apache configuration file, which is the case with mosts shared web hosting providers. But they most of the time gives you access to the htaccess file where you can configure your custom error page or message. With a text editor create an error page, you can name it anything you want, what about 404.html

Inside you can enter something like this:

<html>
	<head>
		<title>Page not found</title>
		<!-- css or anything needed goes here -->
	</head>
	<body>
		<H1>Page not found</H1>
		<p>Sorry but the page you are looking for is not here, please got to our <a href="/">Home page</a></p>
	</body>
</html>

Now add to your htaccess file, this line:

ErrorDocument 404 /404.html

Be sure to have 404.html on the root folder of your server.

Virtual host individual file

If you are working with Ubuntu, you will find two important folders under Apache configuration which are:

  • /etc/apache2/sites-available
  • /etc/apache2/sites-enabled

The latter are symlinks to the former, so you can go to that folder and pick each of files there (each one is one virtual server) and add this line before the </VirtualServer> tag.

ErrorDocument 404 /404.html

Global configuration

You can also configure one path for all Virtual servers. In that case add the line.

ErrorDocument 404 /404.html

To the file /etc/apache2/conf.d/localized-error-pages, you can run this command:

sudo sh -c 'echo "ErrorDocument 404 /404.html" >> etc/apache2/conf.d/localized-error-pages'

Final notes

If you are using a CMS like Drupal or Wordpress they are going to manage 404 errors, and that is a better way, but if your site is a static site, then you can add custom 404 pages this way, and make that page match your design.