HTTP to HTTPS Redirect Rewrite plus port change

Problem this snippet solves:

Wrote this during Cisco ACE to F5 LTM migration where have the following Cisco ACE action list:

action-list type modify http URL_RW_8443
    ssl url rewrite location ".*" sslport 8443

This simply changes the HTTP Loction header in HTTP 301 and 302 responces from HTTP to HTTPS and sets the port. e.g.

http://www.test.com/some/path -> https://www.test.com:8443/some/path

Also found this had to work if the Location Header contained a porte.g.

http://www.test.com:88/some/path -> https://www.test.com:8443/some/path

I have put examples and how the iRule works in the code directly.

How to use this snippet:

This code changes HTTP Location Header in a HTTP Response from HTTP to HTTPS and adds/changes the port to be 8443.

To set a different port locate the line following line and update the ':8443' to the correct port:

lreplace $loc_list 2 2 '[lindex [split [lindex $loc_list 2] ":"] 0]:8443'

Code :

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:8443'
        # e.g. list item 2 = 'www2.test.com' is replaced with 'www2.test.com:8443'
        lreplace $loc_list 2 2 '[lindex [split [lindex $loc_list 2] ":"] 0]:8443'

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

Tested this on version:

11.5
Updated Jun 06, 2023
Version 2.0
No CommentsBe the first to comment