Enhance 404 Error Page, Make it Powerful

As a web developer, we’re so familiar with 404 error, and hate it so much. If  the URL doesn’t exist, the server will return this page to browser to show.

A Funny 404 Error

A Funny 404 Error

Normally, we use default 404 error message to tell visitors they’re looking for pages that don’t exist. Some designers make 404 pages pretty or humorous. And some SEOers redirect visitors by meta tag. In fact, 404 page can do a lot of stuff, that’s what we’re going to discuss.

What can my 404 page do?

1.Shows me a user from where, at what time, trying to visit what unavailable URLs.

We can get current URL and referral URL with PHP, it’s easy to achieve.

2.Shows me why the user wanted to visit this URL, and help me optimize my site.

With the referral URL, it’s intuitive to guess the user’s purpose. Use CodeMug as an example, if the referral URL is http://codemug.com, and the current URL is http://codemug.com/user.php?id=1, this means the visitor may click on some author’s profile page, which no longer exists since it was deleted or blocked, then the page returns 404. So you may need to check if which pages on your site still contain the broken link, simply remove it.

3.Shows me the IP address of the user.

This also basic and easy, just retrieve the visitor’s IP and check its location with GeoIP, you’ll know where your visitors are from.

4.Shows what’s the purpose of the user.

This feature is powerful. If your website is on your own configured server, you need to deal with the secure issues by yourself. Some hackers try all kind of intrusion to hack into the server, you’ll receive a large number of 404 errors, and most of referrals are blank, they’re guessing some sensitive pages with brute-force attack. In this case, you need to block these malicious IPs by adding them to your firewall’s blacklist.

5.Sends me the above messages by Email.

The snippet uses the mail() function, you can also use 3rd-party mailsending classes like sendmail, PHPmail(check out How to send mails with PHPMailer).

6.Filter out unimportant messages

To be honest, I was quite bothered by this snippet in the beginning, because it sends me hundreds of Emails, most of them were generated by normal visits, some of them were generated when search engines were grabbing your contents, and also some from hackers. So I added a filter to do the filtering work. It allows you to filter out unwanted messages by page file extension and IP address.

7.Auto redirects users by 301.

When user encounters the 404 error, we need to guide them to an exist page like home or list page. So how to redirect them? You may say use meta refresh or javascript’s window.location, why bother using 301 ? Well, that’s because we don’t want search engines to consider our redirect as cheating.

8.Informs me if someone is trying to hack my site or my server.

Like I said, it’s a quite an good feature that allows you to notice some potential vulnerabilities. But it depends more on your own security experience.

Sounds like amazing? Okay, let’s see how to establish:

Let’s get started

Save the following code as 404.php, then assign your 404 error to this page in your Apache or nginx configuration file.


#Set your site's URL, no '/' in the end.
$MyURL = (isSet($_SERVER['HTTP_HOST'])) ? Str_iReplace('http://','',StrToLower(rTrim($_SERVER['HTTP_HOST'],'/'))) : 'codemug.com';

#Set your site's domain, no '/' in the end.
$MyDomain = (isSet($_SERVER['HTTP_HOST'])) ? 'http://'.Str_iReplace('http://','',StrToLower(rTrim($_SERVER['HTTP_HOST'],'/'))) : 'http://codemug.com';

//Set timezone, no need to change

Header('Content-type:text/html; charset=utf-8');

	Send Email
		receiver,title,content,(use '\n' to between lines, 70 characters max limited for each line)
		Use PHPmail() function to send emails
Function SendMail($to,$tit,$msg) {
		throw new Exception('Invalid Email address!');

	$msg = str_replace("\n.","\n..",$msg);		//in Windows, lines begin with a single dot will be deleted, so we need to replace single dot to double.

	Return Mail($to,$tit,$msg,'From:someone@gmail.com'."\n".'Content-Type:text/html;charset=utf-8');

$msg='<table cellspacing="0" cellpadding="0" border="0"><tr><td style="padding:5px;background-color:#F57900;font-size:13px;border:2px solid #222;color:#222;">';
$msg.=(isSet($_SERVER['REMOTE_ADDR'])) ? "<b>IP:</b><br><a href='http://ip-lookup.net/index.php?ip={$_SERVER['REMOTE_ADDR']}&action=2' target='_blank'>{$_SERVER['REMOTE_ADDR']}</a><br>" : '';
$msg.="<b>Time:</b><br>".date('Y-m-d H:i:s',time()).'<br><br>';
$msg.=(isSet($_SERVER['REMOTE_HOST'])) ? "<a href='http://ip-lookup.net/index.php?ip={$_SERVER['REMOTE_HOST']}&action=2' target='_blank'>{$_SERVER['REMOTE_HOST']}</a><br><br>" : '<br>';
$msg.=(isSet($_SERVER['HTTP_USER_AGENT'])) ? "<b>User Agent:</b><br>{$_SERVER['HTTP_USER_AGENT']}<br><br>" : '';
$msg.=(isSet($_SERVER['REQUEST_URI'])) ? "<b>Request Page:</b><br>{$MyDomain}{$_SERVER['REQUEST_URI']}<br><br>" : '';
$msg.=(isSet($_SERVER['HTTP_REFERER']) And Trim($_SERVER['HTTP_REFERER'])!='') ? "<b>Referer:</b><br>{$_SERVER['HTTP_REFERER']}<br><br>" : '';

//File extension filter, do filter these media files or they will drive you crazy 

//IP filter, you should filter out search engine spiders

//File extension needed

IF(!In_Array($needEx,$arr) And !In_Array(Trim($_SERVER['REMOTE_ADDR']),$arrIP)) {
	Mail2('someone@gmail.com','404 error from ['.$MyURL.']!',$msg);

Header('HTTP/1.1 301 Moved Permanently');
Header ("Location:{$MyDomain}");

Note: you can always modify these code to meet your needs.


Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>