Using Google Analytics on your web site - the easy way!

Google Analytics is a great tool for monitoring and tracking visitors to your web sites. Perhaps best of all, it's entirely web based - you only need a web browser to access the analysis services it provides.

To enable tracking for your web sites, all you need to do is to embed a small fragment of JavaScript code in every web page. This can be a challenge when your pages are generated by different applications, or technical or procedural difficulties make it difficult to change all the content consistently.

ZXTM can easily solve this problem. A simple TrafficScript rule can be used to embed the JavaScript fragment in every page, regardless of how the page was generated or where the content was stored.

  • You might also be interested in the Integrating Google Search article, which describes how to seamlessly replace a web site search system with Google's.

Enabling Google Analytics Tracking

Once you have created a Google Analytics account, you can create one or more Website Profiles. Each profile has a unique Tracking Code which needs to be inserted into all of the web pages in that profile.

In this example, we're going to enable tracking for two profiles, corresponding to knowledgehub.zeus.com and support.zeus.com:

 Website Profile   Tracking Code 
 knowledgehub.zeus.com  UA-12345-1
 support.zeus.com  UA-12345-2

We need to add the following JavaScript fragment to every web page, just before the closing </body> tag:

<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct="UA-12345-X";
urchinTracker();
</script>

The following TrafficScript response rule performs the following actions:

  • Check that the response is an HTML document:
    We do not need to put the tracking code in other types of response;
  • Check that the response was generated for knowledgehub.zeus.com or support.zeus.com:
    The virtual server running the rule is managing traffic for a large number of websites, and we only want to add the tracking code to these two website.
  • Read the response body, search for the closing </body> tag and insert the JavaScript code.

Configure it as a response rule for the virtual server managing your web traffic, and ensure that it inserts the correct tracking code for each of your profiles:

$contentType = http.getResponseHeader( "Content-Type" );
if( ! string.startsWith( $contenttype, "text/html" ) ) break;
$host = http.getHeader( "Host" );
if( string.startsWith( $host, "knowledgehub.zeus." ) ) {
$uacct = "UA-12345-1";
} else if( string.startsWith( $host, "support.zeus." ) ) {
$uacct = "UA-12345-2";
} else {
break;
}
$body = http.getResponseBody();
$script =
"<script src=\"http://www.google-analytics.com/urchin.js\" " .
"type=\"text/javascript\">\n" .
"</script>\n" .
"<script type=\"text/javascript\">\n" .
"_uacct = \"" . $uacct . "\";\n" .
"urchinTracker();\n" .
"</script>\n";
if( string.regexmatch( $body, "^(.*)</body>(.*?)$", "i" ) ) {
http.setResponseBody( $1 . $script . "</body>" . $2 );
}

We're using this rule on the ZXTM machines balancing traffic to the zeus.com websites, so we can track users on the support and knowledgehub sites without having to modify any of the content on the sites.

Owen Garrett [Zeus Dev Team] 08 March 2006 Bookmark with del.icio.us Post this article to Digg Post this article to reddit Post this article to Facebook Tweet this article 4 comments  

Comments:

This public messageboard is not a forum for technical support. To report technical support problems, please contact our dedicated Support team using the instructions at the bottom of this page.

Comment from: Stuart Shelton [Visitor]
A nice extension is to extend this code so that the Host header/Google Analytics tag pairs can be read from a file. This file, residing in $ZEUSHOME/zxtm/conf/extra/ will have the format "<site regex> <account>" separated by any number of tabs and/or spaces. These expressions are applied, from top to bottom, to the response Host header, and the account number from the first match is added to the page. An example analytics.accounts file might be:
support\.zeus\.com  UA-xxxxx-1
www\.zeus\.com      UA-xxxxx-2
\.zeus\.com         UA-xxxxx-3
The code to achieve this is:
#
# Google Analytics Auto-tagger
#
# Automatically add Google's Analytics Javascript to all returned HTML
# pages.
# 

$debug = 0;
$googlepath = "http://www.google-analytics.com/urchin.js";
$filename = "analytics.accounts";

$contentType = http.getResponseHeader( "Content-Type" );
if( ! string.startsWith( $contenttype, "text/html" ) ) break;
if( "" != http.getHeader( "Content-Range" ) ) break;
http.removeResponseHeader( "Content-MD5" );

$header = http.getHeader( "Host" );

#
# Read in filter settings from external file
#

if( resource.exists( $filename ) ) {

  $mtime = data.get( "ga_mtime" );
  if( "" == $mtime || $mtime != resource.getMTime( $filename )
    || "" == data.get( "ga_fileread" ) ) {

    #
    # Need to (re)read file contents
    #
    log.info( "Google Analytics data stale: Re-reading " . $filename );

    $contents = resource.get( $filename );
    $contents = string.regexsub( $contents, "[ \t]+", " ", "g" );
    $contents = string.regexsub( $contents, "^ ", "", "g" );
    $contents = string.regexsub( $contents, " $", "", "g" );
    $contents = string.regexsub( $contents, " ?\n+ ?", "\n", "g" );

    if( "" != $contents ) {
      $mtime = resource.getMTime( $filename );
      data.set( "ga_mtime", $mtime );
      log.info( "Successfully found and loaded " . $filename
        . ", last modified " . $mtime );

      $counter = 0;

      while( string.regexmatch( $contents
        , "^([^ ]+) (UA-[0-9]{5}-[0-9]{1,2})(\n(.*))?$", "i" ) ) {
        $host = $1;
        $account = $2;
        $contents = $4;
        if( ! string.contains( $host, "#" ) ) {
          data.set( "ga_host" . $counter, $host );
          data.set( "ga_acct" . $counter, $account );
          $counter = $counter + 1;
          log.info( "Found account number " . $account . " for site "
            . $host . " (" . $counter . ")" );
        }
      }


      #
      # Done reading file
      #
      log.info( "Read " . $counter
        . " Google Analytics tags, current memory usage is "
        . data.getMemoryUsage() . " bytes" );
      $counter = $counter - 1;
      data.set( "ga_fileread", $counter );

    } else {
      log.warn( $filename
        . " exists but is blank - no data loaded" );
      data.set( "ga_mtime", "" );
      data.set( "ga_fileread", "" );
    }
  }
} else {
  log.warn( "Cannot read $ZEUSHOME/zxtm/conf/extra/"
    . $filename . " to check tags for " . $header );
  data.set( "ga_mtime", "" );
  data.set( "ga_fileread", "" );
}

#
# Detect whether Host header matches
#
$maxcounter = data.get( "ga_fileread" );
$matched = 0;
$counter = 0;
$acct = "";
if( "" != $maxcounter ) {
  $nexthost = data.get( "ga_host" . $counter );
  if( 1 == $debug ) log.info( "$header is " . $header );
  while( 0 == $matched && "" != $nexthost
      && $counter <= $maxcounter ) {
    if( string.regexmatch( $header, $nexthost ) ) {
      $acct = data.get( "ga_acct" . $counter );
      log.info( "Host " . $header . " matches site "
        . $nexthost . " and account " . $acct );
      $matched = 1;
    } else {
      if( 1 == $debug ) log.info( "Unmatched site: " . $nexthost );
    }
    $counter = $counter + 1;
    $nexthost = data.get( "ga_host" . $counter );
  }
}

#
# Set Google Analytics code if Host header matches
#
if( 0 == $matched ) break;
if( "" == $acct ) break;

if( 1 == $debug ) log.info( "Building response for " . $header . http.getPath() );

$body = http.getResponseBody();
if( string.contains( $body, $googlepath ) ) break;

$script = "\n"
        . "<script src=\"" . $googlepath . "\" type=\"text/javascript\">\n"
        . "</script>\n"
        . "<script type=\"text/javascript\">\n"
        . "_uacct = \"" . $acct . "\";\n"
        . "urchinTracker();\n"
        . "</script>\n";

if( string.regexmatch( $body, "^(.*)</body>(.*?)$", "i" ) ) {
  http.setResponseBody( $1 . $script . "</body>" . $2 );
}
Please note that for ZXTM versions 3.1r1 and prior, Content-Encoding and Transfer-Encoding headers should be removed in a Request Rule before this Response Rule is run, in order to correctly tag compressed responses. In ZXTM 4.0 and above, responses are automatically decompressed if necessary!
Permalink 01 February 2006 @ 22:21
Comment from: karthy [Member] · http://netic.dk
Google Analytics customer numbers is now 6 digits long so the line containing

, "^([^ ]+) (UA-[0-9]{5}-[0-9]{1,2})(\n(.*))?$", "i" ) ) {

should be replaced with

, "^([^ ]+) (UA-[0-9]{5,6}-[0-9]{1,2})(\n(.*))?$", "i" ) ) {

But really nice and usefull script!
Permalink 06 July 2007 @ 12:31
Comment from: Luke [Visitor] · http://Lots. :o)
Is there a updated version of this code to support the new google code which is more complex?
Permalink 17 March 2009 @ 15:51
Comment from: Owen Garrett [Zeus Dev Team]
Hi Luke, The new Google Analytics code is documented here. So, where the code above says
$script = some javascript
change it to something like:
$script = 
   "<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\">".
   "var pageTracker = _gat._getTracker(\"" . $uacct . "\");".
   "pageTracker._trackPageview();".
   "</script>";
Permalink 17 March 2009 @ 17:13
Leave a comment ...
Your email address will not be displayed.
Your URL will be displayed.
This public messageboard is not a forum for technical support. To report technical support problems, please contact our dedicated Support team using the instructions at the bottom of this page.
Options:
 
(Line breaks become <br />)
(Set cookies for name, email & url)

Recently...

Other Resources