Force HTTPS with HAProxy.

This is a short tutorial on how to force HTTPS / SSL with the HAProxy load balancer. Essentially, we want to setup HAProxy so that it redirects all requests on port 80 to port 443.

Redirect all traffic to HTTPS.

Luckily enough, on HAProxy 1.5 and above, you can simply add the following line to your frontend configuration:

#redirect to HTTPS if ssl_fc is false / off.
redirect scheme https code 301 if !{ ssl_fc }

The line above tells our load balancer to perform a 301 Redirect to HTTPS if SSL is off. i.e. If they are sending a regular non-HTTPS request.

Note that we also use the 301 code because it tells the client that the resource in question has been permanently moved to the new HTTPS URL (and that it should stop looking for the old resource). This also tells search engines such as Google that our new HTTPS URL should be indexed instead of the old unsecured URL.

Only force HTTPS for one domain.

If you’re only looking to force HTTPS for a particular domain, you can add the following frontend configuration line to your /etc/haproxy/haproxy.cfg file:

#Redirect to HTTPS if the host domain is www.yourdomain.com
redirect scheme https code 301 if { hdr(Host) -i www.yourdomain.com } !{ ssl_fc }

The line above tells HAproxy to redirect to HTTPS if SSL is off AND the host domain is www.yourdomain.com. Obviously, you will need to change this line to match your own domain name.

Hopefully, you found this guide to be short but useful!

See also: