Replace Host on Original HTTP Request

Hi All,

I’m looking to do the following;

In the HTTP_Request, store the entire request in a variable called orgRequest

If I get a 302 redirect in the response I want to change the header “Host” to the IP address I received in the redirect.

I have a variable called newHost which has the IP address and port of where I want to go, what I don’t know how to do is to replace the “Host” in the original request and resend. What I am currently seeing is that my output in /var/log/ltm shows my orgRequest with the original “Host” header.

Ideally I could do this by invoking the LB_Selected Event, but I don’t know if you can invoke events - does anyone know if this is possible?

Basically what I have looks like this (semi-pseudo code)

HTTP_Request {

set orgRequest [HTTP::request]

}

HTTP_Response {

if 302 redirect

set newHost = Location Header of 302 response

set orgRequest $orgRequest[HTTP::header replace “Host” “$newHost”]

HTTP::retry $orgRequest

}

Cheers,

Conor

Hi Conor,

You could either replace the string within the HTTP::request variable:

set orgRequest [string map {oldhost.example.com newhost.example.com} [HTTP::request]]

Or you could track whether this is a retried request and then use HTTP::header replace Host “newhost.example.com”:

when CLIENT_ACCEPTED {   
       Track whether we're retrying the request   
      set retrying 0   
   }   
   when HTTP_REQUEST {   
      
       Check if some condition is true, where we want to potentially retry the request   
      if {$some_condition}{   
      
          Check if this is a retried request   
         if {$retry}{   
      
             Update the Host header value   
            HTTP::header replace  Host "newhost.example.com"   
      
             Specify a new destination for this request   
            node $new_ip $new_port   
      
         } else {   
            set orgRequest [HTTP::request]    
         }   
      }   
   }   
   when HTTP_RESPONSE {   
      
       Add logic for when to retry the request and set retry to 0 or 1 
   }

I assume you’re not saving the full request for every request? Doing so would unnecessarily use a lot of memory.

Aaron

Aaron,

Thanks for the tips, mate. Good job. Works like a treat!

Cheers,

Conor

If you use string map, you could make the match more specific by including the “Host:” portion:

set orgRequest [string map -nocase [list “Host: oldhost.example.com” “Host: newhost.example.com”] [HTTP::request]]

Aaron