Traefik Middlewares
Everything Traefik does to a request or response between router and service is a middleware: stripping a path prefix, adding headers, redirecting to HTTPS, authentication, rate limiting, IP allow-lists, retries, compression. Middlewares are defined once in the dynamic configuration and attached to routers by name, in order; a chain middleware bundles several so that every router can use the same set.
| Middleware | Does | Nginx / HAProxy equivalent |
|---|---|---|
stripPrefix, addPrefix, replacePathRegex |
change the path | proxy_pass …/;, http-request replace-path |
redirectScheme, redirectRegex |
redirects | return 301, http-request redirect |
headers |
custom request/response headers, CORS, security headers (HSTS, frame options…) | add_header, proxy_set_header |
basicAuth, digestAuth, forwardAuth |
authentication; forwardAuth asks an external service (OAuth2 proxy, Authelia) |
auth_basic, auth_request |
ipAllowList |
allow only some networks (named ipWhiteList before v3) |
allow/deny, ACL on src |
rateLimit, inFlightReq |
requests per period / concurrent requests, per source | limit_req, limit_conn, stick tables |
retry, circuitBreaker |
retry failed attempts; stop sending to a failing service | proxy_next_upstream, observe layer7 |
compress |
gzip, Brotli, zstd | gzip |
buffering |
request/response size limits and buffering | client_max_body_size |
chain |
a named list of middlewares | an include file |
A protected API and a public site
cat > app.py <<'EOF'
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200); self.end_headers()
self.wfile.write(f"app got {self.path} user={self.headers.get('X-Auth-User')} env={self.headers.get('X-Env')}\n".encode())
def log_message(self, *a): pass
HTTPServer(("127.0.0.1", 9000), H).serve_forever()
EOF
python3 app.py &
HASH=$(openssl passwd -apr1 's3cret-pass') # htpasswd-style hash for basicAuth
cat > traefik.yml <<'EOF'
global: {checkNewVersion: false, sendAnonymousUsage: false}
entryPoints:
web: {address: "127.0.0.1:8080"}
traefik: {address: "127.0.0.1:8081"}
api: {insecure: true}
providers:
file: {filename: dynamic.yml, watch: false}
log: {level: ERROR}
EOF
cat > dynamic.yml <<EOF
http:
middlewares:
common:
chain:
middlewares: [security-headers, env-header]
security-headers:
headers:
frameDeny: true
contentTypeNosniff: true
customResponseHeaders:
Server: "" # an empty value removes the header
env-header:
headers:
customRequestHeaders:
X-Env: production
strip-api:
stripPrefix:
prefixes: ["/api"]
api-auth:
basicAuth:
users: ["ada:${HASH}"]
headerField: X-Auth-User # pass the authenticated user to the app
api-limit:
rateLimit:
average: 2 # requests per second, per source IP
burst: 3
office-only:
ipAllowList:
sourceRange: ["10.0.0.0/8"]
routers:
site:
rule: "PathPrefix(\`/\`)"
service: app
middlewares: [common]
api:
rule: "PathPrefix(\`/api\`)"
service: app
middlewares: [common, api-limit, api-auth, strip-api]
admin:
rule: "PathPrefix(\`/admin\`)"
service: app
middlewares: [office-only, common]
services:
app:
loadBalancer:
servers: [{url: "http://127.0.0.1:9000"}]
EOF
traefik --configFile=traefik.yml > traefik.log 2>&1 &
for i in $(seq 100); do curl -sf 127.0.0.1:8081/api/http/routers/admin@file > /dev/null && break; sleep 0.1; done
r() { printf '%-30s -> %s %s\n' "${*/127.0.0.1:8080/}" "$(curl -s -o out.txt -w '%{http_code}' "$@")" "$(head -1 out.txt)"; }
r 127.0.0.1:8080/products
r 127.0.0.1:8080/api/links
r -u ada:wrong 127.0.0.1:8080/api/links
r -u ada:s3cret-pass 127.0.0.1:8080/api/links
r 127.0.0.1:8080/admin/
curl -s -D - -o /dev/null 127.0.0.1:8080/products | grep -iE '^(x-frame|x-content|server)' | tr -d '\r'
sleep 2 # let the bucket refill
echo "10 quick API calls: $(for i in $(seq 10); do curl -s -o /dev/null -w '%{http_code} ' -u ada:s3cret-pass 127.0.0.1:8080/api/links; done)"
grep -c . traefik.log
kill %2 %1/products -> 200 app got /products user=None env=production
/api/links -> 401 401 Unauthorized
-u ada:wrong /api/links -> 401 401 Unauthorized
-u ada:s3cret-pass /api/links -> 200 app got /links user=ada env=production
/admin/ -> 403 Forbidden
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
10 quick API calls: 200 200 200 429 429 429 429 429 429 429
0
- The site got the shared
commonchain only; the API router added rate limiting, authentication and prefix stripping. Order matters:api-limitruns beforeapi-auth, so brute-forcing passwords is rate limited too, andstrip-apicomes last so the app sees/links. basicAuthpassed the user name to the app inX-Auth-User. TheAuthorizationheader itself is still forwarded to the app unless you addremoveHeader: true; decide whether the app should ever see the password.ipAllowListrefused the admin path with403 Forbiddenbecause the session's client is127.0.0.1. Behind another load balancer, setipStrategy.depthso it uses the rightX-Forwarded-Forentry, and configureforwardedHeaders.trustedIPson the entry point.- The rate limit let the burst through, then answered
429until tokens refill at 2 per second. (The earlier API calls, including the failed logins, used up tokens too, hence the pause before the test.) - The log file is empty: at level
ERROR, a healthy Traefik writes nothing. Access logs are separate (Access Log Formats).
Middlewares from other providers
With the Docker provider, the same middlewares are declared as container labels, and in Kubernetes as Middleware custom resources attached to an IngressRoute or, with the Gateway API, through ExtensionRef filters on an HTTPRoute:
# Sample: Traefik's Kubernetes CRD (traefik.io/v1alpha1)
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: api-limit
namespace: linkly
spec:
rateLimit:
average: 5
burst: 3# Sample: Docker labels on a container (with the Docker provider)
labels:
- "traefik.http.routers.linkly.rule=Host(`linkly.example`)"
- "traefik.http.routers.linkly.middlewares=api-limit@file,secure@file"
- "traefik.http.services.linkly.loadbalancer.server.port=8080"Middlewares defined in a file (@file) can be used by routers from Docker or Kubernetes, which is a good way to keep security headers and rate limits in one reviewed place.
Test yourself
Why put api-limit before api-auth in a router's middleware list?
- It is required
- Middlewares run in list order, so password guesses are rate-limited before authentication is checked
- To make auth faster
- It doesn't matter
What is a chain middleware for?
- Load balancing
- Bundling several middlewares under one name so many routers can share the same set
- TLS
- Retries
Traefik v3 renamed which middleware?
- stripPrefix to removePrefix
- ipWhiteList to ipAllowList
- rateLimit to throttle
- headers to header