Referral Tracker

Problem this snippet solves:

Ever wanted to track your referrals in a graphical format without having to write code or modify your application servers? With the referral tracker, it can be added directly you your virtual server and it will begin collecting data immediately. Once you have collected some data, access the admin panel at http://virtual/admin and see a pie chart of your top referrers. When deploying this iRule, don't forget to add the 'authorized_users' data class. Without it, the virtual will return a TCP reset to users. Click here for the accompanying tech tip

Code :

when RULE_INIT {
  set static::response_header "Top referrers"
  set static::response_footer ""

  set referrer_host [URI::host [HTTP::header value Referer]]

  if { $referrer_host eq "" } {
    set referrer_host "none"

  if { [table incr -subtable referrers -mustexist $referrer_host] eq "" } {
    table set -subtable referrers $referrer_host 1 indefinite indefinite
  } else {
    table incr -subtable referrers $referrer_host

  if { [HTTP::path] eq "/admin" } {
    binary scan [md5 [HTTP::password]] H* password

    if { [class lookup [HTTP::username] $::authorized_users] equals $password } {
      log local0. "User [HTTP::username] has been authorized to access virtual server [virtual name]"

      switch -glob [URI::query [HTTP::uri] action] {
        reset_referrers {
          foreach referrer [table keys -subtable referrers] {
            table delete -subtable referrers $referrer

          HTTP::respond 200 content "$static::response_header 

Referrer counters reset

Back to referrer chart
$static::response_footer" } report_referrers - default { set chart ",20&" append chart "chco=003399,CCFFFF&chtt=Top%20referrers%20for%20[HTTP::host]" set chd "" set chl "" foreach referrer [table keys -subtable referrers] { append chd "," [table lookup -subtable referrers $referrer] append chl "|" [URI::encode "$referrer ([table lookup -subtable referrers $referrer] hits)"] } append chart "&" "chd=t:[string trimleft $chd ,]" append chart "&" "chl=[string trimleft $chl |]" HTTP::respond 200 content "$static::response_header
Reset referrer counters
$static::response_footer" } } } else { if { [string length [HTTP::password]] != 0 } { log local0. "User [HTTP::username] has been denied access to virtual server [virtual name]" } HTTP::respond 401 WWW-Authenticate "Basic realm=\"Secured Area\"" } } } # iRule Test Code priority 10 when HTTP_REQUEST { set test_referrers [list "" "" "" "" "" "" "" "" "" "" "" "none"] set rand_test_referrer [lindex $test_referrers [expr {int(rand()*[llength $test_referrers])}]] log local0. "The randomly selected referrer was $rand_test_referrer" HTTP::header replace "Referer" "http://$rand_test_referrer" HTTP::header replace "Host" "" }
Published Mar 18, 2015
Version 1.0

Was this article helpful?

No CommentsBe the first to comment