Include Google Analytics in your static HTML website
July 10, 2007A few months ago I was assigned to a project where a company, while their new site was being developed, wanted to track the visitors on their website for marketing purposes. The only problem was that their current website was constructed with Frontpage a few years ago and consisted of hundreds of static HTML pages. Since I'm (very) lazy I was not planning to copy paste the whole thing, I figured out a way to include the GA code in every static html page.
First, I wrote a .htaccess file which rewrites all (including files in subdirs) .html and .htm pages to addgoogleanalytics.php:
RewriteEngine on
RewriteRule ^(.*).html?$ addgoogleanalytics.php?file=$0
Wow, it that all? Yes it is. So helloworld.html will be rewrited to addgoogleanalytics.php?file=helloworld.html, and the user won't even notice. Now, take a look at addgoogleanalytics.php:
<?php /* Open the given file and add the google analytics code */ $sData = file_get_contents($_GET['file']); $sData = str_replace("</body>", " <script src=\"http://www.google-analytics.com/urchin.js\" type=\"text/javascript\"> </script> <script type=\"text/javascript\"> _uacct = \"UA-1808705-3\"; urchinTracker(); </script> </body>", $sData); echo $sData; ?>
Enjoy.
Add to:


Google Analytics is using a new script for even more advanced features. I adjusted the script for the ga.js code. Don’t forget to change the UA-code.
“, ”
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\”));
var pageTracker = _gat._getTracker(\”UA-1808705-3\”);
pageTracker._initData();
pageTracker._trackPageview();
“, $sData);
echo $sData;
?>
Comment by Marco de Moulin — January 23, 2008 @ 5:30 pm