Handling 404s with Google 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> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-xxxxxxx-1"); pageTracker._trackPageview(trackPageview(); } catch(err) {}</script>
http://www.yoursite.com/20092734nv3A.php

- 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:

pageTracker._trackPageview(trackPageview();
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!
Leave a Reply