Handling 404s with Google Analytics

11 Mar, 2009  |  Written by  |  under Analytics

I normally set up sites to just log 404s and check the log files for problems, which is fine for me, but hard for clients.  Here’s how I recently set up a site so the client’s marketing folks could spot 404s on their own:

Google Analytics works through JavaScript in the browser.  As the browser loads each page on a site, it calls home to Google and gives Analytics a bunch of information about what the user is doing. Here’s the usual block of code:

<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl/." : "http://www/.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-xxxxxxx-1");
} catch(err) {}</script>
Works like a champ for normal pages, but your 404 page is often special. To test, head to a made-up URL on your site, and see what it looks like:
Chances are, this will give you a terrible web server or browser error message, and that needs to be corrected so you can take control of the 404 page. If you’re using Apache with the default config, it’ll look like:

  • To fix this for Apache, use this directive in httpd.conf:
ErrorDocument 404 /404.html
  • For ColdFusion, use the ColdFusion admin to set the missing template handler for .cfm files.
  • For IIS, use the MMC management tool, click to ‘Custom Errors’, and change 404 to: URL and /404.cfm or whatever your 404 page is, like this:


Once you have this set, your 404s will go to a page you can clean up, like this:
It’s best to have a mini sitemap on this page, so folks can find what they were actually looking for, of course!
Now, back to Analytics.  On this 404 page, we’ll change the JavaScript to send ourselves some clues about the 404 in Analytics. Change this line:

to this:

pageTracker._trackPageview(trackPageview(“/404.html?page=” + document.location.pathname + document.location.search + “&from=” + document.referrer);

Now your 404s should show up in Analytics as if they were on a “virtual” page called 404.html, with parameters including the missing page AND the referer (so you can ask for the link to be fixed). This will show up in your ‘Top Content’ report.

Very handy!

No Responses so far | Have Your Say!

Leave a Reply