Rewrite HTTP Redirect Hostname

Problem this snippet solves:

Intercepts server-set redirect responses & rewrites the specified hostname.

See the ProxyPass and ProxyPass Lite iRules for related examples.

Code :

# To redirect to a different hostname than that set in an the origin server redirect:

 when HTTP_RESPONSE {

   # Check if server response is a redirect
   if { [HTTP::header is_redirect]} {

      # Log original and updated values
      log local0. "Original Location header value: [HTTP::header value Location],\
         updated: [string map -nocase {myold.hostname.com mynew.hostname.com} [HTTP::header value Location]]"

      # Do the update, replacing myold.hostname.com with mynew.hostname.com
      HTTP::header replace Location [string map -nocase {myold.hostname.com mynew.hostname.com} [HTTP::header value Location]]
   }
}

# Note: Here is an example which rewrites the protocol in redirects from http:// to https:// and rewrites the host in redirects from the server IP address to the Host name the client used in the request.

when HTTP_REQUEST {

   # Save host name (use VS IP if no HTTP host header was found
   if {[HTTP::host] eq ""}{
      set host [IP::local_addr]
   } else {
      set host [HTTP::host]
   }
}
when HTTP_RESPONSE {

   # Check if server response is a redirect
   if { [HTTP::header is_redirect]} {

      # Log original and updated values
      log local0. "Original Location header value: [HTTP::header value Location],\
         updated: [string map -nocase "http:// https:// [IP::server_addr] $host" [HTTP::header value Location]]"

      # Do the update, replacing http:// with https:// and the server IP with the host or VS IP
      HTTP::header replace Location [string map -nocase "http:// https:// [IP::server_addr] $host" [HTTP::header value Location]]
   }
}
Published Mar 18, 2015
Version 1.0
No CommentsBe the first to comment