Forum Discussion

Maurice_G_'s avatar
Maurice_G_
Icon for Employee rankEmployee
Jan 10, 2012

Redirect to different CDN based on GeoLocation

I added a STREAM profile to the virtual server and associated the following iRule.

 

 

 

when HTTP_REQUEST {

 

STREAM::disable

 

if { ([matchclass [IP::client_addr] equals $::test_group]) or ( [whereis [IP::client_addr] country] equals "CN") } {

 

log local0. "User is in country [whereis [IP::client_addr] country]"

 

set CDN1 "example-s.cdn1.net"

 

set CDN2 "example-s.cdn2.net"

 

}

 

}

 

 

 

when HTTP_RESPONSE {

 

if {[HTTP::header Location] contains "$CDN1"}{

 

HTTP::header replace Location [string map "$CDN1 $CDN2" [HTTP::header Location]]

 

}

 

STREAM::expression "@$CDN1@$CDN2@"

 

log local0. "A user in country [whereis [IP::client_addr] country] has been redirected from CDN1 to CDN2"

 

STREAM::enable

 

}

 

when STREAM_MATCHED {

 

log local0. "HOORAY"

 

}

 

 

 

I am looking for feedback for anything I may have missed or suggestions to make it better.

 

Thanks

 

  • Here are a few minor edits:

    
    when HTTP_REQUEST {
    
     Disable the stream filter by default
    STREAM::disable
    
     Check if the client IP is in the test_group data group or in China
    if { ([matchclass [IP::client_addr] equals test_group]) or ( [whereis [IP::client_addr] country] equals "CN") } {
    log local0. "User is in country [whereis [IP::client_addr] country]"
    set CDN1 "example-s.cdn1.net"
    set CDN2 "example-s.cdn2.net"
    } else {
     Track that we will not rewrite the response content
    set CDN1 ""
    }
    }
    when HTTP_RESPONSE {
    
     Rewrite redirects
    if  {[HTTP::is_redirect] and [HTTP::header Location] contains "$CDN1"}{
    HTTP::header replace Location [string map "$CDN1 $CDN2" [HTTP::header Location]]
    }
     Check if we are rewriting the response content
    if {$CDN1 ne ""}{
    
     Set the find/replace for the stream filter and enable it
    STREAM::expression "@$CDN1@$CDN2@"
    log local0. "A user in country [whereis [IP::client_addr] country] has been redirected from CDN1 to CDN2"
    STREAM::enable
    }
    } 
    when STREAM_MATCHED {
    log local0. "HOORAY"
    }
    

    Aaron
  • Colin_Walker_12's avatar
    Colin_Walker_12
    Historic F5 Account
    If the version is new enough (10 or newer) I'd switch to class match and static:: variables, too.

     

     

    Colin