HTTP to HTTPS Location rewrite with custom port

Problem this snippet solves:

The SSL port is assigned in the following line:

lreplace $loc_list 2 2 [lindex [split [lindex $loc_list 2] ":"] 0]:80

change the ':80' to any required port to remove to remove any port assigned within the Location Header.

How to use this snippet:


Code :

# Rewrites the HTTP Location header in a HTTP Reponse from HTTP to HTTPS and a none standard port to the end of the hostname
# e.g. Location Header 'http://www.test.com/path1/path2/index.html' will be changed to 'https://www.test.com:80/path1/path2/index.html'

when HTTP_RESPONSE {
    if {[string tolower [HTTP::header Location]] starts_with "http://" }{
        #Splits the Location Header string into a list
        # e.g. http://www.test.com/path1/path2/index.html = 'http:', '', 'www.test.com', 'path1', 'path2', 'index.html'
        set loc_list [split [HTTP::header Location] "/"]

        # Replaces list location 0 (first item) with 'https:' 
        # e.g. list item 0 = 'http:' and is replaced with 'https:'
        lreplace $loc_list 0 0 "https:"

        # Appended the port number to list location 2 (the FQDN), if a port is already defined this will replaced 
        # e.g. list item 2 = 'www.test.com:897' is replaced with 'www.test.com:80'
        # e.g. list item 2 = 'www2.test.com' is replaced with 'www2.test.com:80'
        lreplace $loc_list 2 2 [lindex [split [lindex $loc_list 2] ":"] 0]:80

        # List items are joined back together with '/' inserted and set at the new HTTP Location Header
        # e.g. list = 'https:', '', 'www.test.com:80', 'path1', 'path2', 'index.html' becomes 'https://www.test.com:80/path1/path2/index.html'
        HTTP::header replace Location [join $loc_list "/"] 
    }
}

Tested this on version:

11.5
Updated Jun 06, 2023
Version 2.0
  • Getting the following error on BIG-IP v11.6.0.8.0.482:

     

    01070151:3: Rule [/Common/HTTP_to_HTTPS_Location_rewrite_with_custom_port] error: /Common/HTTP_to_HTTPS_Location_rewrite_with_custom_port:14: error: [wrong args][lreplace [$loc_list 0 0 "https:"]] /Common/HTTP_to_HTTPS_Location_rewrite_with_custom_port:19: error: [wrong args][lreplace [$loc_list 2 2 [lindex [split [lindex $loc_list 2] ":"] 0]:80]]

     

  • Same comment as above. What gives? Does anyone read these comments? This irule, as written, generates the errors Pavel Stoyanov pasted above. How do we fix this?

     

  • lreplace command doesn't replace any value in list but returns a new list with replaced value.

    you can use this command :

    set loc_list [lreplace $loc_list 0 2 https {} [lindex [split [lindex $loc_list 2] ":"] 0]:80]
    

    or

    set loc_list [lreplace $loc_list 0 2 https {} [getfield [lindex $loc_list 2] ":" 0]:80]