HAProxy Rewrite Insecure Redirects

How to rewrite 3XX response redirects specifying http, to https using HAProxy

This is often a problem where HAProxy is configured for SSL/TLS but the origin web servers are not. When the server sends a redirect, the link in the Location header uses the http:// scheme and not the https:// scheme. This breaks things when your proxy is not also ‘handling’ HTTP and redirecting to HTTPS (which is far from efficient anyway as that’s two redirects).

You can use something like this in a frontend or backend:

rspirep ^Location:\ http://(.*)  Location:\ https://\1  if { status 301 } OR { status 302 } OR { status 303 }

The rspirep command completely replaces the value of the header. The domain name and URL are maintained through the use of a POSIX Compliant Regular Expression (PCRE) that stores the content matching the search string .* by enclosing it in brackets (). This content is then inserted in the replacement text with \1.

This can be done multiple times if necessary.