HAProxy – How to run http and https on the same port

Want to have your app run on one just the one port but work in both http and https mode? It’s easily done. You’ll first have to have a normal frontend for ports 80 and 443 similar to the following:

frontend unsecured *:80
timeout client 1d
maxconn 20000

default_backend default

frontend secured
maxconn 20000
bind   0.0.0.0:443 ssl crt /etc/haproxy/proxycert.cert

default_backend default

You probably already have this setup if you’re running HAProxy, no need to change it if you do.

Now to make another port (9000 in this example) work with both http and https just do the following:

frontend newport
maxconn 20000

bind   0.0.0.0:9000

mode tcp
option tcplog

tcp-request inspect-delay 100ms
tcp-request content accept if HTTP
tcp-request content accept if { req.ssl_hello_type 1 }

use_backend forward_http if HTTP
default_backend forward_https

backend forward_http
mode tcp
server serverhttp 127.0.0.1:80

backend forward_https
mode tcp
server serverhttps 127.0.0.1:443

It simply takes 100ms (this could be lowered but I didn’t want things to accidentally break) to detect what mode the connection is in. If it’s in HTTP it forwards the request to itself on port 80 and if not it forwards to itself on port 443.