Web servers and networking · Advanced · 24 min
Terminate TLS and route by hostname with HAProxy
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · HAProxy 3.4 LTS
You will have HAProxy 3.4 serving three HTTPS hostnames from one address, choosing certificates by SNI, routing on Host and path, redirecting HTTP, passing one service's TLS straight through and limiting requests per client IP.
On this page
A single HAProxy instance can sit at the edge of a server and answer HTTPS for several names at once. It finishes the TLS handshake itself (TLS termination), reads the decrypted request, and sends it as plain HTTP to whichever backend owns that hostname and path. The backends never touch a private key, and you renew certificates in one place.
Not every service should be decrypted at the edge. A secrets store or a payment service may be required to hold its own key, so HAProxy has to pass those connections through untouched while still terminating everything else on the same port 443. It can do both, because the hostname a client wants is visible in plain text in the TLS handshake (the SNI field) before any encryption starts.
In this tutorial you build that edge for three made-up names under the reserved .test domain:
app.example.test: the main site. Requests for/static/go to a separate static backend.api.example.test: an API backend.vault.example.test: a service that terminates its own TLS. HAProxy passes it through.
All the backends are small Python servers on the same machine, and a local certificate authority signs the certificates, so you can test everything with curl --resolve before any DNS exists. In production the backends sit on private addresses and the certificates come from a public CA.
Step 1 · Install HAProxy 3.4 and start the backends
Ubuntu 26.04's own archive carries the HAProxy 3.2 LTS branch. This tutorial uses 3.4, the current LTS branch, from the PPA kept by HAProxy's Debian maintainer. The config below is written for 3.4; if you stay on 3.2, run haproxy -c after each change and read any warning it prints. If you followed /tutorials/load-balance-web-servers-with-haproxy, HAProxy 3.4 is already installed and the first block only adds the tools this tutorial uses.
sudo apt update
sudo apt install -y software-properties-common
sudo add-apt-repository -y ppa:vbernat/haproxy-3.4
sudo apt install -y 'haproxy=3.4.*' curl openssl python3 socat
haproxy -v | head -n 1The first line of haproxy -v reads something like HAProxy version 3.4.8-1ppa1~resolute. Packages from a PPA get updates through apt upgrade like any other, as long as the PPA stays in your sources.
Now write one small backend script. It answers with its own name and the request headers HAProxy is about to set, so every check later in the tutorial can read them. Given a certificate and key, it serves HTTPS instead of HTTP.
mkdir -p ~/haproxy-tls-demo
cat > ~/haproxy-tls-demo/backend.py <<'PY'
import ssl
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
name, port = sys.argv[1], int(sys.argv[2])
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
h = self.headers
body = (
f"{name} path={self.path} host={h.get('Host')} "
f"xff={h.get('X-Forwarded-For')} proto={h.get('X-Forwarded-Proto')}\n"
).encode()
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
if len(sys.argv) == 5:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(sys.argv[3], sys.argv[4])
server.socket = ctx.wrap_socket(server.socket, server_side=True)
server.serve_forever()
PY
nohup python3 ~/haproxy-tls-demo/backend.py app 8001 > /dev/null 2>&1 &
nohup python3 ~/haproxy-tls-demo/backend.py static 8002 > /dev/null 2>&1 &
nohup python3 ~/haproxy-tls-demo/backend.py api 8003 > /dev/null 2>&1 &
sleep 1Check it worked
curl -s http://127.0.0.1:8001/ | grep '^app '
curl -s http://127.0.0.1:8002/ | grep '^static '
curl -s http://127.0.0.1:8003/ | grep '^api 'Each backend prints its name, then xff=None proto=None, because nothing sits in front of it yet.
Step 2 · Create a local CA and certificates for three hostnames
A local CA lets you issue certificates that curl trusts when you point it at the CA file, without touching the system trust store. Keys are created inside a subshell with umask 077, so they are private from the moment they exist and your shell's own umask is left alone.
mkdir -p ~/haproxy-tls-demo/pki
cd ~/haproxy-tls-demo/pki
(
umask 077
openssl req -x509 -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -noenc \
-keyout ca.key -out ca.crt -days 30 -subj "/CN=HAProxy demo local CA"
for host in app.example.test api.example.test vault.example.test; do
openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -noenc \
-keyout "$host.key" -out "$host.csr" -subj "/CN=$host"
printf '%s\n' \
"subjectAltName=DNS:$host" \
"basicConstraints=critical,CA:FALSE" \
"keyUsage=critical,digitalSignature" \
"extendedKeyUsage=serverAuth" > "$host.ext"
openssl x509 -req -in "$host.csr" -CA ca.crt -CAkey ca.key -CAcreateserial \
-days 30 -extfile "$host.ext" -out "$host.crt"
done
)
cd ~HAProxy reads a certificate and its key from one PEM file. Give it its own directory, owned by root and closed to everyone else. Each file is created empty with mode 600 before the key goes in. Only app and api go here: HAProxy never holds the vault key.
sudo install -d -m 700 /etc/haproxy/certs
for host in app.example.test api.example.test; do
sudo install -m 600 /dev/null "/etc/haproxy/certs/$host.pem"
cat ~/haproxy-tls-demo/pki/$host.crt ~/haproxy-tls-demo/pki/$host.key \
| sudo tee "/etc/haproxy/certs/$host.pem" > /dev/null
doneYou could point HAProxy at the whole directory with crt /etc/haproxy/certs/, and it would pick a certificate by the names inside each one. A crt-list is more explicit: one line per certificate, the hostnames it may answer for, and optional per-certificate TLS settings in square brackets. The first line is also the default certificate for clients that send no SNI.
sudo tee /etc/haproxy/crt-list.txt > /dev/null <<'LIST'
/etc/haproxy/certs/app.example.test.pem app.example.test
/etc/haproxy/certs/api.example.test.pem api.example.test
LISTCheck it worked
openssl verify -CAfile ~/haproxy-tls-demo/pki/ca.crt ~/haproxy-tls-demo/pki/*.example.test.crt
sudo ls -l /etc/haproxy/certsopenssl verify prints OK for all three certificates, and both PEM files in /etc/haproxy/certs show -rw------- and root root.
Step 3 · Terminate TLS and route on Host and path
This step replaces /etc/haproxy/haproxy.cfg. Keep a copy of the packaged file first, because the last step restores it. If this server already runs HAProxy for something else, merge the sections below into your file instead.
test -f /etc/haproxy/haproxy.cfg.orig || sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.orig
sudo tee /etc/haproxy/haproxy.cfg > /dev/null <<'CFG'
global
log /dev/log local0
chroot /var/lib/haproxy
stats socket /run/haproxy/admin.sock mode 660 level admin
user haproxy
group haproxy
daemon
ssl-default-bind-options ssl-min-ver TLSv1.2
defaults
log global
mode http
timeout connect 5s
timeout client 30s
timeout server 30s
frontend ft_https
bind :443 ssl crt-list /etc/haproxy/crt-list.txt strict-sni alpn h2,http/1.1
option httplog
# Replace anything the client sent: backends must be able to trust these.
http-request set-header X-Forwarded-For %[src]
http-request set-header X-Forwarded-Proto https
acl host_app hdr(host),host_only -i app.example.test
acl host_api hdr(host),host_only -i api.example.test
acl is_static path_beg /static/
use_backend be_static if host_app is_static
use_backend be_app if host_app
use_backend be_api if host_api
default_backend be_unknown_host
backend be_app
server app1 127.0.0.1:8001
backend be_static
server static1 127.0.0.1:8002
backend be_api
server api1 127.0.0.1:8003
backend be_unknown_host
http-request return status 404 content-type text/plain string "unknown host"
CFG
sudo haproxy -c -f /etc/haproxy/haproxy.cfghaproxy -c prints nothing and exits with status 0 when the file is valid; a problem is printed as an [ALERT] or [WARNING] line naming the file and line number. Add -V if you want it to print Configuration file is valid. Apply it:
sudo systemctl reload haproxyWhat each part does:
strict-snimakes HAProxy refuse the handshake when the requested name matches no line of the crt-list, instead of handing out the default certificate. Scanners that connect by IP address get nothing.alpn h2,http/1.1offers HTTP/2 to clients. HAProxy still talks HTTP/1.1 to the backends.- The ACLs route on the
Hostheader, not on SNI. After decryption theHostheader is the name the request is really for; a browser can reuse one HTTP/2 connection for several names its certificate covers, so SNI alone can point at the wrong site.host_onlystrips any:portfrom the value, and-imakes the match case-insensitive. use_backendrules run top to bottom and the first match wins, which is why the more specific static rule comes first.set-headerreplaces rather than appends. With an appending rule, a client could send its ownX-Forwarded-For: 10.0.0.1and an app that reads the first value would believe it.
Check it worked
curl --resolve sends the request to 127.0.0.1 while using the real hostname for SNI, the Host header and certificate checks:
CA=~/haproxy-tls-demo/pki/ca.crt
curl -s --cacert "$CA" --resolve app.example.test:443:127.0.0.1 https://app.example.test/ | grep '^app '
curl -s --cacert "$CA" --resolve app.example.test:443:127.0.0.1 https://app.example.test/static/logo.svg | grep '^static '
curl -s --cacert "$CA" --resolve api.example.test:443:127.0.0.1 https://api.example.test/v1/items | grep '^api .*proto=https'
curl -s --cacert "$CA" --resolve app.example.test:443:127.0.0.1 -H 'X-Forwarded-For: 10.0.0.1' https://app.example.test/ | grep 'xff=127.0.0.1 '
curl -s --cacert "$CA" --resolve app.example.test:443:127.0.0.1 -H 'Host: other.example.test' https://app.example.test/ | grep 'unknown host'You see app, static and api answer their own paths with proto=https, a forged X-Forwarded-For replaced by the real client address 127.0.0.1, and unknown host for a Host header no rule matches. Now ask for a name with no certificate:
if curl -s --cacert ~/haproxy-tls-demo/pki/ca.crt --resolve other.example.test:443:127.0.0.1 https://other.example.test/; then
echo "unexpected: handshake succeeded"; false
else
echo "handshake refused, as expected"
fistrict-sni refuses the handshake, so curl fails before any HTTP is sent. To see which names HAProxy has loaded, ask the stats socket:
echo "show ssl sni" | sudo socat stdio /run/haproxy/admin.sock | grep 'example.test'Both app.example.test and api.example.test appear, each next to its PEM file.
Step 4 · Redirect HTTP to HTTPS and send HSTS
Visitors who type a bare name arrive on port 80. Give them a permanent redirect to the same path over HTTPS, and tell browsers with an HSTS header to use HTTPS on their own next time. HSTS also saves the redirect round trip on every later visit, which is worth having on slow, high-latency mobile connections, common for users of many African sites on prepaid data.
Start with a short max-age such as 300 seconds. A browser that has seen the header refuses plain HTTP for that long, so a mistake with a one-year value locks visitors out for a year. Raise it to 31536000 once every name serves HTTPS cleanly, and add includeSubDomains only when every subdomain does.
Add a port 80 frontend and one line to ft_https. The file below is the whole config again:
sudo tee /etc/haproxy/haproxy.cfg > /dev/null <<'CFG'
global
log /dev/log local0
chroot /var/lib/haproxy
stats socket /run/haproxy/admin.sock mode 660 level admin
user haproxy
group haproxy
daemon
ssl-default-bind-options ssl-min-ver TLSv1.2
defaults
log global
mode http
timeout connect 5s
timeout client 30s
timeout server 30s
frontend ft_http
bind :80
option httplog
http-request redirect scheme https code 301
frontend ft_https
bind :443 ssl crt-list /etc/haproxy/crt-list.txt strict-sni alpn h2,http/1.1
option httplog
http-request set-header X-Forwarded-For %[src]
http-request set-header X-Forwarded-Proto https
http-response set-header Strict-Transport-Security "max-age=300"
acl host_app hdr(host),host_only -i app.example.test
acl host_api hdr(host),host_only -i api.example.test
acl is_static path_beg /static/
use_backend be_static if host_app is_static
use_backend be_app if host_app
use_backend be_api if host_api
default_backend be_unknown_host
backend be_app
server app1 127.0.0.1:8001
backend be_static
server static1 127.0.0.1:8002
backend be_api
server api1 127.0.0.1:8003
backend be_unknown_host
http-request return status 404 content-type text/plain string "unknown host"
CFG
sudo haproxy -c -f /etc/haproxy/haproxy.cfgsudo systemctl reload haproxyA reload starts new workers with the new file and lets the old ones finish their open connections, so nothing is dropped.
Check it worked
curl -sI --resolve app.example.test:80:127.0.0.1 http://app.example.test/static/logo.svg > ~/haproxy-tls-demo/redirect.txt
grep -E '^HTTP/1.1 301' ~/haproxy-tls-demo/redirect.txt
grep -i '^location: https://app.example.test/static/logo.svg' ~/haproxy-tls-demo/redirect.txt
curl -s -D - -o /dev/null --cacert ~/haproxy-tls-demo/pki/ca.crt --resolve app.example.test:443:127.0.0.1 https://app.example.test/ > ~/haproxy-tls-demo/hsts.txt
grep -E '^HTTP/2 200' ~/haproxy-tls-demo/hsts.txt
grep -i 'strict-transport-security: max-age=300' ~/haproxy-tls-demo/hsts.txtThe first request returns HTTP/1.1 301 with location: https://app.example.test/static/logo.svg, keeping the path. The second is a normal GET that prints only the response headers (-D - writes them out, -o /dev/null drops the body): HTTP/2 200 and the HSTS header.
Step 5 · Pass one service's TLS straight through
So far port 443 is an HTTP frontend that decrypts everything. To let vault.example.test keep its own key, port 443 has to look at the handshake before deciding whether to decrypt. The new layout:
ft_tls_inowns port 443 in TCP mode. It waits for the TLS ClientHello and reads the SNI name from it withreq.ssl_sni, without decrypting anything.- Connections for
vault.example.testgo byte for byte to the vault service on 127.0.0.1:9443, which does its own TLS. - Everything else goes to
ft_https, which now listens on 127.0.0.1:10443 only and terminates TLS as before.
The hop from step 1 to step 3 would hide the visitor's address: ft_https would see every connection coming from HAProxy itself, and X-Forwarded-For and per-IP limits would break. The PROXY protocol fixes this. send-proxy-v2 on the inner server line puts a small header with the real client address in front of the connection, and accept-proxy on the inner bind line reads it, so src is the visitor again.
Start the vault service with its own certificate and key:
nohup python3 ~/haproxy-tls-demo/backend.py vault 9443 \
~/haproxy-tls-demo/pki/vault.example.test.crt ~/haproxy-tls-demo/pki/vault.example.test.key > /dev/null 2>&1 &
sleep 1Then write the new config:
sudo tee /etc/haproxy/haproxy.cfg > /dev/null <<'CFG'
global
log /dev/log local0
chroot /var/lib/haproxy
stats socket /run/haproxy/admin.sock mode 660 level admin
user haproxy
group haproxy
daemon
ssl-default-bind-options ssl-min-ver TLSv1.2
defaults
log global
mode http
timeout connect 5s
timeout client 30s
timeout server 30s
frontend ft_http
bind :80
option httplog
http-request redirect scheme https code 301
frontend ft_tls_in
bind :443
mode tcp
option tcplog
tcp-request inspect-delay 5s
tcp-request content accept if { req.ssl_hello_type 1 }
use_backend be_vault_passthrough if { req.ssl_sni -i vault.example.test }
default_backend be_tls_terminate
backend be_vault_passthrough
mode tcp
server vault1 127.0.0.1:9443
backend be_tls_terminate
mode tcp
server local_https 127.0.0.1:10443 send-proxy-v2
frontend ft_https
bind 127.0.0.1:10443 accept-proxy ssl crt-list /etc/haproxy/crt-list.txt strict-sni alpn h2,http/1.1
option httplog
http-request set-header X-Forwarded-For %[src]
http-request set-header X-Forwarded-Proto https
http-response set-header Strict-Transport-Security "max-age=300"
acl host_app hdr(host),host_only -i app.example.test
acl host_api hdr(host),host_only -i api.example.test
acl is_static path_beg /static/
use_backend be_static if host_app is_static
use_backend be_app if host_app
use_backend be_api if host_api
default_backend be_unknown_host
backend be_app
server app1 127.0.0.1:8001
backend be_static
server static1 127.0.0.1:8002
backend be_api
server api1 127.0.0.1:8003
backend be_unknown_host
http-request return status 404 content-type text/plain string "unknown host"
CFG
sudo haproxy -c -f /etc/haproxy/haproxy.cfgsudo systemctl reload haproxytcp-request inspect-delay 5s gives a client up to five seconds to send its ClientHello, and the accept rule moves on as soon as a complete one (req.ssl_hello_type 1) arrives, so normal clients wait no time at all. Because HAProxy never decrypts vault traffic, it cannot add headers or HSTS there, and the vault service sees connections from HAProxy's address. If that service understands the PROXY protocol, add send-proxy-v2 to its server line as well.
Check it worked
CA=~/haproxy-tls-demo/pki/ca.crt
curl -s --cacert "$CA" --resolve vault.example.test:443:127.0.0.1 https://vault.example.test/ | grep '^vault .*proto=None'
if curl -s -D - -o /dev/null --cacert "$CA" --resolve vault.example.test:443:127.0.0.1 https://vault.example.test/ | grep -qi strict-transport-security; then
echo "unexpected: HSTS on the vault"; false
else
echo "no HSTS header from the vault"
fi
curl -s --cacert "$CA" --resolve app.example.test:443:127.0.0.1 https://app.example.test/ | grep '^app .*xff=127.0.0.1 proto=https'The vault answers with proto=None and no HSTS header, which proves the request reached it untouched, and the certificate curl accepted was the vault's own, a file HAProxy never read. The app still gets the client address and proto=https through the PROXY protocol hop.
Step 6 · Limit requests per client IP with a stick table
A stick table is an in-memory table HAProxy keeps per key, here the client IP, with counters you choose. Track each client's HTTP request rate over a sliding 10 second window and answer 429 Too Many Requests above 20. Choose real limits from your traffic logs; a shared office or mobile carrier can put many people behind one address, so leave room for that.
Add three lines to ft_https, right after option httplog. In full:
sudo tee /etc/haproxy/haproxy.cfg > /dev/null <<'CFG'
global
log /dev/log local0
chroot /var/lib/haproxy
stats socket /run/haproxy/admin.sock mode 660 level admin
user haproxy
group haproxy
daemon
ssl-default-bind-options ssl-min-ver TLSv1.2
defaults
log global
mode http
timeout connect 5s
timeout client 30s
timeout server 30s
frontend ft_http
bind :80
option httplog
http-request redirect scheme https code 301
frontend ft_tls_in
bind :443
mode tcp
option tcplog
tcp-request inspect-delay 5s
tcp-request content accept if { req.ssl_hello_type 1 }
use_backend be_vault_passthrough if { req.ssl_sni -i vault.example.test }
default_backend be_tls_terminate
backend be_vault_passthrough
mode tcp
server vault1 127.0.0.1:9443
backend be_tls_terminate
mode tcp
server local_https 127.0.0.1:10443 send-proxy-v2
frontend ft_https
bind 127.0.0.1:10443 accept-proxy ssl crt-list /etc/haproxy/crt-list.txt strict-sni alpn h2,http/1.1
option httplog
stick-table type ip size 100k expire 30s store http_req_rate(10s)
http-request track-sc0 src
http-request deny deny_status 429 if { sc_http_req_rate(0) gt 20 }
http-request set-header X-Forwarded-For %[src]
http-request set-header X-Forwarded-Proto https
http-response set-header Strict-Transport-Security "max-age=300"
acl host_app hdr(host),host_only -i app.example.test
acl host_api hdr(host),host_only -i api.example.test
acl is_static path_beg /static/
use_backend be_static if host_app is_static
use_backend be_app if host_app
use_backend be_api if host_api
default_backend be_unknown_host
backend be_app
server app1 127.0.0.1:8001
backend be_static
server static1 127.0.0.1:8002
backend be_api
server api1 127.0.0.1:8003
backend be_unknown_host
http-request return status 404 content-type text/plain string "unknown host"
CFG
sudo haproxy -c -f /etc/haproxy/haproxy.cfgsudo systemctl reload haproxystick-tableholds up to 100,000 addresses and forgets one 30 seconds after its last request.track-sc0 srccounts every request against the client address. This is why the PROXY protocol in the previous step matters: without it, every visitor would share HAProxy's own address and one busy client would block everyone.deny_status 429tells well-behaved clients to slow down rather than reporting an error.
A reload starts with an empty table. Several HAProxy servers behind one address can share their tables through a peers section, which this tutorial does not cover.
Check it worked
Send 30 requests in a burst and count the status codes:
for i in $(seq 1 30); do
curl -s -o /dev/null -w '%{http_code}\n' --cacert ~/haproxy-tls-demo/pki/ca.crt \
--resolve app.example.test:443:127.0.0.1 https://app.example.test/
done | sort | uniq -c | tee ~/haproxy-tls-demo/codes.txt
grep -E '^ +[0-9]+ 429$' ~/haproxy-tls-demo/codes.txt
echo "show table ft_https" | sudo socat stdio /run/haproxy/admin.sock | grep 'key=127.0.0.1'You see something like 20 200 and 10 429: the first 20 requests pass and the rest are refused. The show table line for key=127.0.0.1 shows the client's current http_req_rate(10000). Wait ten seconds and requests pass again.
Step 7 · Clean up
These commands stop the demo backends, delete the demo certificates and the crt-list, and put back the packaged HAProxy config you saved earlier. Skip the restore if you have since merged real sites into haproxy.cfg. The [b] in the pattern stops pkill matching a shell or script whose command line contains the same text.
pkill -f 'haproxy-tls-demo/[b]ackend.py'
sudo cp /etc/haproxy/haproxy.cfg.orig /etc/haproxy/haproxy.cfg
sudo rm -r /etc/haproxy/certs /etc/haproxy/crt-list.txt
sudo rm /etc/haproxy/haproxy.cfg.origThe packaged file has only global and defaults sections and no bind line. It still passes the check:
sudo haproxy -c -f /etc/haproxy/haproxy.cfgWith no frontend, though, HAProxy has nothing to listen on, so stop it rather than reload it:
sudo systemctl stop haproxyrm -r ~/haproxy-tls-demoCheck it worked
if pgrep -f 'haproxy-tls-demo/[b]ackend.py'; then echo "a backend is still running"; false; else echo "backends stopped"; fi
if curl -s --max-time 3 -o /dev/null http://127.0.0.1/; then echo "port 80 still answers"; false; else echo "port 80 closed"; fiYou see backends stopped and port 80 closed. HAProxy itself stays installed. If you installed it for this tutorial and no longer need it, use the purge and remove-PPA commands at the end of /tutorials/load-balance-web-servers-with-haproxy.
Next steps
- Spread traffic over several copies of each backend with health checks in
/tutorials/load-balance-web-servers-with-haproxy. - Read the certificates you just issued, and debug chain problems, with
/tutorials/understand-tls-certificates-and-chains-with-openssl. - Compare the same redirect and HSTS rules written for Nginx in
/tutorials/redirect-http-to-https-and-www-in-nginx.
Related tutorials
- Load balance web servers with HAProxyYou will put HAProxy 3.4 in front of three web backends on Ubuntu 26.04, with HTTP health checks, weights, a backup server, a password-protected stats page and a server drained through the runtime API.
- How TLS certificates work: chains, SANs and expiry, with opensslYou will build a small certificate authority with OpenSSL 3.5, read and verify the chain it issues, serve it from Nginx, and have a script that warns you before a certificate expires.
- Redirect HTTP to HTTPS and www to the bare domain in NginxYou will send every plain-HTTP and www request on Nginx 1.30 to https://example.com in a single 301 hop, with the path and query string kept, and have a script that checks all four combinations.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials