Google Analytics + apache configuration mini - howto
I’ve been thinking of setting up google analytics on my site for a while now and have finally taken a few moments to get started. I'm curious to see where folks are coming from and am kind of tired of writing one-off scripts to grep my apache logs.
If, like me, you have a site made of many many html pages, this one’s for you. (DO please make a backup of your site and configuration files before you start).
_uacct = "XX-XXXXXXX-X";
Each html document you want google to track will need to include that file’s text immediately before the </body> tag through the placement of a small SSI tag.
It will look something like this:
<!--#include virtual="/data/included.html" -->
To do such a massive replace, we’ll need a little Perl (yes, Juan PERL!) and bash.
perl -p -i -e 's/<body<!--#include virtual=\"\/data\/included.html\" -->\n <body/g' `find . |grep \.html`
This finds all html files, then performs a mass insertion before the </body> tag with the SSI include. Apache will take the include and replace it with the contents of the file.
If SSI isn't yet configured on your apache box, there is a simple set of tricks that will make life MUCH easier. Assuming that you have compiled mod_include (most apache installations have this), you simply need to add
Options +Includesto your site configuration. I placed it in my virtual hosts file along with my other Options directives. The real juice is here: place
XBitHack onin your apache configuration as well. This will make apache parse any file (looking for SSI includes) with the execute (remember your unix permissions?) bit enabled. You will then set the execute bit on all of your html pages like so:
chmod +x `find . |grep \.html`
Note: XBitHack will not work on windows for obvious reasons. There is no executable bit on windows. See the apache tutorial referenced above for other methods to enable SSI if you're on windows.