Use Google Analytics on every page using Apache

I’ve recently set up my own server at home, containing all the pictures and data I did not want to host on Facebook, Hyves (dutch Facebook), Picasa or even Photobucket (ugh!) any longer. Sometimes when I’m at home I hear my server crunching some numbers although I would not even be using it, so I was wondering what exactly it was doing. I started looking for a PHP apache/server request monitoring application so I could ‘check’ what the server would be doing or serving, but could not really find anything useful. I then decided to just use Google analytics.

I have multiple applications running on the server (phpmyadmin for database administration, ampache for streaming music, a svn directory, the excellent Deluge web client, the great eXtplorer filemanager and the wonderful Gallery3 image gallery) so it was not very feasible to edit every template and inject the required G.A. javascript.

Apache however has enough modules that make our life easier and I found this little explanation by Oliver Zheng explaining how to setup Apache so it injects a string on every served page.

Configure apache using Mod_substitute

First, you have to enable the subtitution module in apache. (For me) this was as easy as issuing a

sudo a2enmod substitute

Then, tell apache to insert a snippet on every page:
<VirtualHost *:80>
...
<Location />
AddOutputFilterByType SUBSTITUTE text/html text/plain
Substitute "s|</body>|<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-1234567-1');pageTracker._setDomainName('.yoursite.com');pageTracker._trackPageview();} catch(err) {}</script></body>|i"
</Location>
</VirtualHost>

Note that the substitution string needs to consist of a single line only. Replace the UA-XXXXXX-X code with your Google Analytics tracking number and replace .yourwebsite.com with your actual website address.

Finally, restart apache. (May differ across platforms..)

sudo /etc/init.d/apache2 restart

The first page visits will be recorded somewhere within 24 hours.

Other

A module has been written for Apache that does exactly the same, albeit a bit cleaner. It can be found here: https://github.com/dragon3/mod_google_analytics (I have not this one)

Kirill Minkovich has written about this as well: http://cadlab.cs.ucla.edu/~kirill/analytics.html

2 Responses - Add Yours+

  1. Jochem says:

    >I started looking for a PHP apache/server request monitoring application so I could ‘check’ what the server would be doing or serving, but could not really find anything useful.

    Never heard of log files?

    http://httpd.apache.org/docs/2.2/logs.html#accesslog

Leave a Reply