TExcelTAD

ACLs & Routing

HAProxy's routing language is built from fetches (values taken from the connection or request: path, header, client address, cookie, TLS SNI), converters (functions applied to them: lower, map, field), and ACLs (named conditions that test them). Rules then act on conditions: choose a backend, deny, redirect, set a header. It reads almost like English once you know the pieces, and it is much more expressive than Nginx's location matching.

ACLs

text
acl NAME FETCH[,converter…] [flags] [operator] VALUE …
Fetch + match True when
path_beg /api/ the path starts with /api/ (path_end, path_reg, path_dir too)
path -m str /healthz the path is exactly /healthz (-m beg/end/sub/reg/dir/dom select the method)
hdr(host) -i shop.test the Host header equals shop.test, case-insensitive (-i)
req.hdr(user-agent) -m sub curl the User-Agent contains curl
src 10.0.0.0/8 192.168.0.0/16 the client address is in one of the networks
method POST PUT DELETE the request method
url_param(debug) -m found the query string has debug
req.cook(beta) -m str 1 the cookie beta is 1
ssl_fc_sni -i api.shop.test the TLS SNI name (also works in TCP mode)

Several values in one ACL are ORed. In a rule, ACL names next to each other are ANDed, || ORs, ! negates, and conditions can also be written inline as anonymous ACLs: if { path_beg /admin/ }.

Rules

Rule Example
use_backend use_backend be_api if is_api (first match wins; then default_backend)
http-request deny http-request deny deny_status 403 if is_admin !from_office
http-request redirect http-request redirect scheme https code 301 unless { ssl_fc }
http-request return http-request return status 200 content-type text/plain string "ok" if { path /healthz }
http-request set-header / del-header http-request set-header X-Request-Start t=%Ts
http-request set-path / replace-path http-request replace-path /api/v1/(.*) /api/v2/\1
http-response set-header headers on the way back

http-request rules run in order, top to bottom, before use_backend is evaluated.

A routing table in one frontend

bash · try it yourself
cat > app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.end_headers(); self.wfile.write(f"{sys.argv[2]} got {self.path}\n".encode())
    do_POST = do_GET
    def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 web &
python3 app.py 9002 api &
python3 app.py 9003 beta-web &
for p in 9001 9002 9003; do for i in $(seq 50); do curl -s 127.0.0.1:$p/ > /dev/null && break; sleep 0.1; done; done
cat > haproxy.cfg <<'EOF'
global
  pidfile haproxy.pid
defaults
  mode http
  timeout connect 2s
  timeout client 10s
  timeout server 10s

frontend fe_web
  bind 127.0.0.1:8080
  acl host_api   hdr(host),field(1,:) -i api.shop.test
  acl path_api   path_beg /api/
  acl is_admin   path_beg /admin
  acl from_vpn   req.hdr(x-test-src) -m ip 10.8.0.0/16     # stands in for "src 10.8.0.0/16"
  acl beta_user  req.cook(beta) -m str 1
  acl old_api    path_beg /api/v1/

  http-request return status 200 content-type text/plain string "ok\n" if { path /healthz }
  http-request deny deny_status 403 if is_admin !from_vpn
  http-request redirect code 308 location /api/v2%[path,regsub(^/api/v1,)] if old_api
  http-request set-header X-Route api if host_api || path_api

  use_backend be_api  if host_api || path_api
  use_backend be_beta if beta_user
  default_backend be_web

backend be_web
  server web 127.0.0.1:9001
backend be_api
  http-request replace-path /api(/.*) \1                   # strip the /api prefix for the API service
  server api 127.0.0.1:9002
backend be_beta
  server beta 127.0.0.1:9003
EOF
haproxy -c -f haproxy.cfg && haproxy -D -f haproxy.cfg
r() { p=$1; shift; printf '%-15s %-28s -> ' "$p" "$*"
      curl -s -o out.txt -w '%{http_code} %{redirect_url}' "$@" "127.0.0.1:8080$p"; echo " $(head -1 out.txt)" | sed 's/  */ /g'; }
r /products
r /api/orders
r /orders        -H "Host: api.shop.test:8080"
r /products      -b "beta=1"
r /admin/users
r /admin/users   -H "X-Test-Src: 10.8.3.4"
r /api/v1/orders -X POST
r /healthz
kill $(cat haproxy.pid) %1 %2 %3
Configuration file is valid
/products                                    -> 200  web got /products
/api/orders                                  -> 200  api got /orders
/orders         -H Host: api.shop.test:8080  -> 200  api got /orders
/products       -b beta=1                    -> 200  beta-web got /products
/admin/users                                 -> 403  <html><body><h1>403 Forbidden</h1>
/admin/users    -H X-Test-Src: 10.8.3.4      -> 200  web got /admin/users
/api/v1/orders  -X POST                      -> 308 http://127.0.0.1:8080/api/v2/orders
/healthz                                     -> 200  ok

Things worth noticing:

  • hdr(host),field(1,:) takes the Host header and cuts off the port with the field converter, so api.shop.test:8080 matches. Without it, the ACL would compare the whole header, port included.
  • The /admin rule needs both conditions: is_admin !from_vpn is "admin path AND NOT from the VPN".
  • The redirect builds its target with a sample expression %[path,regsub(^/api/v1,)]: the path with the old prefix removed. The 308 keeps the POST method (redirect codes).
  • /healthz is answered by HAProxy itself, without a backend: useful for the load balancer in front of HAProxy.
  • Rules are evaluated in order, and use_backend lines are checked top to bottom: the beta cookie only applies to requests that aren't API calls.

In production, test the client address with src (the TCP source) rather than a header; the session uses a header only because every request in the sandbox comes from 127.0.0.1. Behind another proxy, have that proxy send the PROXY protocol (accept-proxy on HAProxy's bind line) so that src is the real client, or read req.hdr_ip(x-forwarded-for,-1) (the last address added) only on a port that only the trusted proxy can reach.

Maps instead of long ACL lists

Fifty hosts each going to their own backend become a lookup file instead of fifty ACLs:

text
# hosts.map  (key  value)
shop.test        be_web
api.shop.test    be_api
beta.shop.test   be_beta
text
frontend fe_web
  use_backend %[req.hdr(host),field(1,:),lower,map(/etc/haproxy/hosts.map,be_web)]

The map file is loaded at start and can be changed at runtime through the Runtime API (add map, set map), so adding a tenant needs no reload.

Test yourself

http-request deny if is_admin !from_vpn — when is a request denied?

  1. When it is an admin request OR not from the VPN
  2. When it is an admin request AND not from the VPN
  3. Never
  4. When it comes from the VPN

Two use_backend rules both match a request. Which backend is used?

  1. The last one
  2. The first one in the configuration
  3. Both, round-robin
  4. The default_backend

Why use map() for host-to-backend routing with many tenants?

  1. It is required above 10 ACLs
  2. One rule looks up the backend in a file, which can also be updated at runtime without a reload
  3. Maps are encrypted
  4. ACLs can't match hosts