Archive for 2008

Best way to integrate Google Analytics

Thursday, November 6th, 2008

This is the best solution to integrate Google Analytics into your site. It uses ideas and code from the following 2 sites:

Here is the improved snippet:

<script type="text/javascript" src=""></script>
<script type="text/javascript">
    if (typeof(_gat)=='object')
            _gat._getTracker("UA-1234567-8")._trackPageview()}, 1500);


  1. Does not use document.write
  2. Fixes the “_gat is not defined” issue
  3. Delayed GA access (1.5 second) so the page load time is not affected
  4. Very concise

Another improvement would be to cache ga.js locally to avoid the DNS lookup.

Logging website subsections with Apache

Saturday, April 26th, 2008

This is a typical VirtualHost for in Apache HTTP Server:

    DocumentRoot /home/
    ErrorLog /home/
    CustomLog /home/ "combined"

This CustomLog directive will produce something like this on the logfile: - - [08/Aug/2007:16:12:54 +0300] GET /foo/index.html HTTP/1.1 - - [08/Aug/2007:16:12:54 +0300] GET /bar/index.html HTTP/1.1 - - [08/Aug/2007:16:12:54 +0300] GET /bar/about.html HTTP/1.1

Suppose that you wanted to log requests for /foo and /bar subsections in 2 separate files. That way you (or your client) may find it easier later on to analyze web traffic for the subsites individually.

What you can do is log conditionally using environment variables that you’ve set using SetEnvIf based on the request.

SetEnvIf Request_URI "/foo.*" subsite_foo
SetEnvIf Request_URI "/bar.*" subsite_bar
CustomLog /home/ combined env=subsite_foo
CustomLog /home/ combined env=subsite_bar

This works nice, but not when the urls for your individual subsites look like this:

That’s because the Request_URI does not contain the query string (whatever comes after the ? character).

The solution comes with a little bit of RewriteCond magic, which helps us set an environment variable using ${QUERY_STRING}:

RewriteEngine on
RewriteCond %{QUERY_STRING} .*site=foo.*
RewriteRule (.*) $1 [E=subsite_foo:1]
RewriteCond %{QUERY_STRING} .*site=bar.*
RewriteRule (.*) $1 [E=subsite_bar:1]
CustomLog /home/ combined env=subsite_foo
CustomLog /home/ combined env=subsite_bar

Happy logging…