HTTP To HTTPS Redirect_302

Problem this snippet solves:

Redirects all traffic to same hostname, same URI over https by issuing a redirect with status 302 (Moved Temporarily).

Apply to HTTP virtual server to redirect all traffic to same hostname (stripping port if it exists), same URI over HTTPS. (Do not apply to shared/wildcard virtual server responding to HTTPS traffic, or infinite redirect will occur. Create separate virtual servers on port 80 and port 443, and apply this iRule ONLY to the port 80 HTTP-only virtual server. No iRule is needed on the port 443 HTTPS virtual server.)

How to use this snippet:

when HTTP_REQUEST {
  HTTP::redirect https://[getfield [HTTP::host] ":" 1][HTTP::uri]
}

The above rule may be modified to function on a shared virtual server by testing TCP::local_port and redirecting only if the request came in over port 80:

when HTTP_REQUEST {
  if { [TCP::local_port] == 80 }{
    HTTP::redirect "https://[getfield [HTTP::host] ":" 1][HTTP::uri]"
  }
}

Here is another option which handles HTTP requests which don't have a Host header value. In such a case, the VIP's IP address is used for the host in the redirect.

Code :

when HTTP_REQUEST {

   # Check if Host header has a value
   if {[HTTP::host] ne ""}{

      # Redirect to the requested host and URI (minus the port if specified)
      HTTP::redirect "https://[getfield [HTTP::host] ":" 1][HTTP::uri]"

   } else {

      # Redirect to VIP's IP address
      HTTP::redirect "https://[IP::local_addr][HTTP::uri]"
   }
}
Published Mar 18, 2015
Version 1.0
No CommentsBe the first to comment