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. ->

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

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 :

    if {[string tolower [HTTP::header Location]] starts_with "http://" }{
        #Splits the Location Header string into a list
        # e.g. = 'http:', '', '', '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 = '' is replaced with ''
        # e.g. list item 2 = '' is replaced with ''
        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:', '', '', 'path1', 'path2', 'index.html' becomes ''
        HTTP::header replace Location [join $loc_list "/"] 

Tested this on version:

Updated Jun 06, 2023
Version 2.0

Was this article helpful?

No CommentsBe the first to comment