The following is a URL handling iRule that is kind of generic where the mapping between the URL and the nodes is done externally through the Data Group List for safe maintenance during operation.
The code is also published on F5 Dev Central at: https://devcentral.f5.com/Wiki/iRules.URL_Based_redirection_iRule.ashx
iRule code:
when HTTP_REQUEST {
# You need to set a data group configuration using the following convention
# redirect-key:node-ip:node-port
# e.g. myapplication:10.10.10.2:8008
# Pool name
set pool “my-pool-name”
# Base URL to filter out all unnecessary requests
set base_url “/path/to/my/application”
log “Request: [HTTP::uri] from [IP::client_addr]”
# verify that pool is active and base URL matches
if {([active_members $pool] > 0) and ([HTTP::uri] contains “$base_url”)} {
set live_members [active_members -list $pool]
# log “live_members $live_members”
# parse the URI and fetch the key for redirection
# in the example I used the 2nd key
set dest_node [lindex [split [HTTP::uri] “/”] 2]
# log “destination node:$dest_node”
# find the redirection key in the data group
set idx [matchclass $::my-data-group contains $dest_node] #log "idx=$idx"
# check it key is in the conf
if {$idx > 0} {
set cfg [lindex $::data-group-name [expr $idx – 1]];
# log “cfg $cfg”;
set node_ip [lindex [split $cfg “:”] 1];
# log “node_ip $node_ip”;
set node_port [lindex [split $cfg “:”] 2];
# log “node_port $node_port”;
# check if the desired node is active, then send the
# request to it, otherwise send to pool to an alternate server
if {$live_members contains [list $node_ip $node_port]} {
log “Sending URI:[HTTP::uri] DEST:$dest_node at $node_ip $node_port”
node $node_ip $node_port
} else {
log “Sending [HTTP::uri] DEST:$dest_node to $pool”
pool $pool
}
} else {
# this is the case were redirect key is not in the conf
log “Sorry, Rejecting $dest_node not in conf.”
reject
}
} else {
# well, pool is down…
log “Sorry, $pool is DOWN”
}
}