Recipe 9.7 Notification on Error Conditions


You want to receive email notification when there's an error condition on your server.


Point the ErrorDocument directive to a CGI program that sends mail, rather than to a static document:

ErrorDocument 404 /cgi-bin/404.cgi

404.cgi looks like the following:

#!/usr/bin/perl use Mail::Sendmail; use strict; my $message = qq~ Document not found: $ENV{REQUEST_URI} Link was from: $ENV{HTTP_REFERER} ~; my %mail = (             To => '',             From => '',             Subject => 'Broken link',             Message => $message,             ); sendmail(%mail); print "Content-type: text/plain\n\n"; print "Document not found. Admin has been notified";


This recipe is provided as an example, rather than as a recommendation. On a web site of any significant size or traffic level, actually putting this into practice generates a substantial quantity of email, even on a site that is very well maintained. This is because people mistype URLs, and other sites, over which you have no control, will contain incorrect links to your site. It may be educational, however, to put something like this in place, at least briefly, to gain an appreciation for the scale of your own web site.

The ErrorDocument directive will cause all 404 (Document Not Found) requests to be handled by the specified URL, and so your CGI program gets run and is passed environment variables that will be used in the script itself to figure out what link is bad and where the request came from.

The script used the Mail::Sendmail Perl module to deliver the email message, and this module should work fine on any operating system. The module is not a standard part of Perl, so you may have to install it from CPAN ( A similar effect can, of course, also be achieved in PHP or any other programming language.

The last two lines of the program display a very terse page for the user, telling him that there was an error condition. You may wish, instead, to have the script redirect the user to some more informative and attractive page elsewhere on your web site. This could be accomplished by replacing those last two lines with something like the following:

print "Location:\n\n";

This would send a redirect header to the client, which would display the specified URL to the user.

See Also


Apache Cookbook
Apache Cookbook: Solutions and Examples for Apache Administrators
ISBN: 0596529945
EAN: 2147483647
Year: 2006
Pages: 215

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: