Forum Discussion

Yogeshtaneja's avatar
Yogeshtaneja
Icon for Nimbostratus rankNimbostratus
Jan 22, 2020

Irule to set a pool on the basis of value in X-forwarded-for

Hi ,

I am setting up something, in which the requirement is I need to decide a pool on the basis of ip listed in X-forwarded-for header in the http request.

For this I configured 3 data group list named test_ipranges_1 , test_ipranges_2 & test_ipranges_3. But when i am writing the irule, it is giving me error, can someone help me out with this. Below is the code that i have written:

 

when HTTP_REQUEST {

   if { class match -value [HTTP::header "X-forwarded-for"] equals test_ipranges_1 } {

     pool pool1

   } elseif { class match -value [HTTP::header "X-forwarded-for"] equals test_ipranges_2 } {

     pool pool2

   } elseif { class match -value [HTTP::header "X-forwarded-for"] equals test_ipranges_3 } {

     pool pool3

   } else {

   pool default

   }

}

1 Reply

  • Hi Yogeshtaneja, i would probably change your code to something like this.

     

    when HTTP_REQUEST {
    if { [HTTP::header values "X-Forwarded-For"] ne "" } {
             set clientip [getfield [HTTP::header X-Forwarded-For] "," 1]
             # set the variable ONLY if an X-FORWARDED-FOR header is there
       catch {
                 # doing a catch to control any errors linked to the code 
                 if { [class match $clientip equals test_ipranges_1] } {
                     pool pool1
                   } elseif { [class match $clientip equals test_ipranges_2] } {
                     pool pool2
                    } elseif { [class match $clientip equals test_ipranges_3] } {
                     pool pool3
                   } else {
                     pool default
                   }
                }
           }
                     pool default
                 # in case the X-Fowarded-For was not properly set
                 # or the catch provided an error
    }

    To be honest, i would have done this slightly differently, by putting in the datagroup, multiple entries of IPs (so in a way, merging your 3 datagroups into 1 here), and adding in the value, the pool you target. So in that case, you do a single check, and if it exists, you retrieve the destination pool in a variable and use pool $variable as the selected pool