Forum Discussion

Annsar_Akhtar's avatar
Annsar_Akhtar
Icon for Nimbostratus rankNimbostratus
Nov 14, 2016

Irule to capture only part of the url and perform a redirect

Hi All

 

I have a requirement from our development team as we look into moving to a new url structure to accommodate new responsive pages.

 

The request is to redirect the url only if the url is three backslashes deep and persist the url (ignoring any url which are five backslashes deep).

 

i.e. , redirect to (I am hoping to use /level1 as the starting anchor point

 

I have had a read through the forum and have tried the getfield to split the url and then store the level as variable to then apply a string map, below is what I have got so far:

 

when HTTP_REQUEST { set level3 [getfield [HTTP::uri] "/" 4]]] if { [string tolower [HTTP::uri]] starts_with "/level1" } { HTTP::respond 302 Location [string map -nocase {/$level3 /newlevel/$level3} [HTTP::uri]] } }

 

I am wondering whether it is worth looking at the regex approach but I have read that can be cpu intensive.

 

Thanks

 

4 Replies

  • Hi Annsar, too much "]" after getfield instruction. Try this:

     

    when HTTP_REQUEST {

     

    set level3 [getfield [HTTP::uri] "/" 4]

     

    if { [string tolower [HTTP::uri]] starts_with "/level1" } {

     

    HTTP::respond 302 Location [string map -nocase {/$level3 /newlevel/$level3} [HTTP::uri]]

     

    }

     

    }

     

     

    regards Leonardo

     

  • Thanks Leonardo, I am now getting a redirect loop as it seem to be matching up the level multiple times for a single request.

     

    I can see from the log statement that the split is working but is seems to be triggering for all request at level3 I guess.

     

    Is there a way to only capture what the url is enter into the browser?

     

  • Hi, you can try this:

    when HTTP_REQUEST { 
    set level3 [getfield [HTTP::uri] "/" 4] 
    set newlevel "newlevel/$level3"
    if {( [string tolower [HTTP::uri]] starts_with "/level1" ) and not [string tolower [HTTP::uri]] contains "$newlevel"} { 
        HTTP::respond 302 Location [string map -nocase "$level3 $newlevel" [HTTP::uri]] 
    
    } 
    

    }

  • The log statement I had added already, I just didn't post it.

     

    Thanks for second reply that seem to work better and gives me a good starting point, below is the amended irule as it had some syntax error incase its useful for others:

     

    when HTTP_REQUEST { set level3 [getfield [HTTP::uri] "/" 4] set newlevel "newlevel/$level3" if {( [string tolower [HTTP::uri]] starts_with "/level1" ) &&!([string tolower [HTTP::uri]] contains "$newlevel")} { HTTP::respond 302 Location [string map -nocase "$level3 $newlevel" [HTTP::uri]]

     

    } }

     

    Thanks again