Traefik guide · All security headers

Traefik security headers: one tested middleware for all six

All six security headers on Traefik in one tested headers middleware: CSP, HSTS, X-Frame-Options, Referrer-Policy, Permissions-Policy and nosniff, labels or file.

  • By
  • Updated
  • 7 min read
  • Tested on Traefik 2.11, 3.6 and 3.7
$ curl -sI https://example.com/missing
status
HTTP/2 404
content-security-policy
default-src 'self'; …
strict-transport-security
max-age=31536000; …
x-frame-options
DENY
referrer-policy
strict-origin-when-cross-origin
permissions-policy
camera=(), microphone=(), …
x-content-type-options
nosniff

All 6 present on error pages too

In short5 points
  • Define one headers middleware with contentSecurityPolicy, stsSeconds, stsIncludeSubdomains, frameDeny, referrerPolicy, permissionsPolicy and contentTypeNosniff, and list it on every HTTPS router.
  • Traefik replaces the application's values for these headers, on its pages and 404s, and adds them to its own 502s. Nothing needs hiding, unlike Nginx, Apache or Caddy.
  • For per-path values, add a router for the path and list its override middleware before security-headers. Listed after, the defaults win.
  • Attaching the middleware to the entry point covers every router, but per-path overrides then stop working.
  • Traefik passes on the application's Server header, version included. Add customResponseHeaders with Server: "" to avoid the 5-point WebSec0 penalty.

The short answer

Define one headers middleware with the six headers, and list it on the router of your site. In a dynamic configuration file:

YAML
http:
  middlewares:
    security-headers:
      headers:
        contentSecurityPolicy: "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests"
        stsSeconds: 31536000
        stsIncludeSubdomains: true
        frameDeny: true
        referrerPolicy: "strict-origin-when-cross-origin"
        permissionsPolicy: "camera=(), microphone=(), geolocation=(), payment=(), usb=(), serial=(), hid=(), bluetooth=(), midi=(), display-capture=(), accelerometer=(), gyroscope=(), magnetometer=(), browsing-topics=()"
        contentTypeNosniff: true

  routers:
    site:
      rule: "Host(`example.com`)"
      entryPoints: [websecure]
      tls: {}
      service: backend
      middlewares: [security-headers]

With Docker labels:

YAML
services:
  app:
    image: nginx:1.30
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.app.rule=Host(`example.com`)"
      - "traefik.http.routers.app.entrypoints=websecure"
      - "traefik.http.routers.app.tls=true"
      - "traefik.http.routers.app.middlewares=security-headers"
      - "traefik.http.middlewares.security-headers.headers.contentSecurityPolicy=default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests"
      - "traefik.http.middlewares.security-headers.headers.stsSeconds=31536000"
      - "traefik.http.middlewares.security-headers.headers.stsIncludeSubdomains=true"
      - "traefik.http.middlewares.security-headers.headers.frameDeny=true"
      - "traefik.http.middlewares.security-headers.headers.referrerPolicy=strict-origin-when-cross-origin"
      - "traefik.http.middlewares.security-headers.headers.permissionsPolicy=camera=(), microphone=(), geolocation=(), payment=(), usb=(), serial=(), hid=(), bluetooth=(), midi=(), display-capture=(), accelerometer=(), gyroscope=(), magnetometer=(), browsing-topics=()"
      - "traefik.http.middlewares.security-headers.headers.contentTypeNosniff=true"

Every configuration on this page was run on Traefik 2.11, 3.6 and 3.7, in front of Nginx containers, and checked with curl on a page, a 404, a static file, an application that sends its own headers, an application that was down and paths with their own values. The labels were tested on all three versions too.

Two of these options need a rollout before they go live in this form. The CSP blocks every script, style and connection that is not on your own origin: start it in report-only mode, as the Content-Security-Policy guide for Traefik explains. The HSTS value is a final one: start with a short stsSeconds, as the HSTS guide for Traefik explains.

What each option does

Option Header sent WebSec0 points Details
contentSecurityPolicy Content-Security-Policy: only your own origin, no plugins, no framing 25 CSP on Traefik
stsSeconds, stsIncludeSubdomains Strict-Transport-Security: max-age=31536000; includeSubDomains 20 HSTS on Traefik
frameDeny X-Frame-Options: DENY 15 X-Frame-Options on Traefik
referrerPolicy Referrer-Policy: full URL on your origin, origin only elsewhere 15 Referrer-Policy on Traefik
permissionsPolicy Permissions-Policy: camera, microphone, location, devices and sensors off 15 Permissions-Policy on Traefik
contentTypeNosniff X-Content-Type-Options: nosniff 10 X-Content-Type-Options on Traefik

There is no always flag to remember. In our test, the six headers were on the application’s pages and 404s, and on Traefik’s own 502 when the application was down. The entry point’s HTTP to HTTPS redirect carried none of them, which is fine: browsers ignore HSTS over plain HTTP, and that response has no page to protect. A 404 from Traefik for a host that no router matches has none either, and no body.

Before you start

A middleware does nothing until a router lists it. Check which routers exist and which middlewares they use, in the Traefik dashboard or in your labels:

Shell
docker inspect --format '{{json .Config.Labels}}' <container> | tr ',' '\n' | grep traefik

Then check three things the middleware can break:

  • Scripts and styles your CSP does not allow. Run the policy in report-only mode first.
  • Subdomains without HTTPS. includeSubDomains makes browsers refuse them.
  • Files served with the wrong type. nosniff blocks a script or stylesheet whose Content-Type does not match.

Also remove the features your site uses from permissionsPolicy, such as camera for a video call page, or give those pages their own value (step 3).

After each change, read the Traefik logs. An option that a version does not know makes Traefik reject the whole dynamic file, and every router in it answers 404.

Step 1: list it on every HTTPS router

Each router needs the middleware, including a router that only redirects, such as example.com to www.example.com. With labels, a middleware defined on one container can be used by the routers of others as security-headers@docker; with the file provider, as security-headers@file.

To cover every router at once, attach the middleware to the HTTPS entry point in the static configuration:

YAML
entryPoints:
  websecure:
    address: ":443"
    http:
      middlewares:
        - security-headers@file

Our test then returned the six headers on every router without listing the middleware on any of them. The cost comes in step 3: an entry point middleware modifies the response after the router’s middlewares, so per-path values on routers had no effect. Use the entry point only if every path gets the same values.

Step 2: the application’s headers are replaced

When the application sends its own security headers, the headers middleware replaces them. Our test, with an application that sent weak values for all six, such as Referrer-Policy: unsafe-url and X-Frame-Options: SAMEORIGIN, returned each header once, with the middleware’s value, on pages and 404s. Nginx, Apache and Caddy keep both copies unless you hide the application’s; Traefik needs no extra line.

If the application must own one header, such as a CSP with per-request nonces, leave that option out of the middleware.

Step 3: different values for some paths

Some pages need a different value: an embeddable widget, a password reset page, a video call. Add a router per path, with a middleware that holds only the new values. Traefik gives priority to the longer rule, so these routers win for their paths:

YAML
http:
  middlewares:
    embed-headers:
      headers:
        contentSecurityPolicy: "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self' https://partner.example; upgrade-insecure-requests"
        customResponseHeaders:
          X-Frame-Options: ""
    reset-headers:
      headers:
        referrerPolicy: "no-referrer"
    meet-headers:
      headers:
        permissionsPolicy: "camera=(self), microphone=(self), geolocation=(), payment=(), usb=(), serial=(), hid=(), bluetooth=(), midi=(), display-capture=(), accelerometer=(), gyroscope=(), magnetometer=(), browsing-topics=()"

  routers:
    site-embed:
      rule: "Host(`example.com`) && PathPrefix(`/embed/`)"
      entryPoints: [websecure]
      tls: {}
      service: backend
      middlewares: [embed-headers, security-headers]
    site-reset:
      rule: "Host(`example.com`) && PathPrefix(`/reset/`)"
      entryPoints: [websecure]
      tls: {}
      service: backend
      middlewares: [reset-headers, security-headers]
    site-meet:
      rule: "Host(`example.com`) && PathPrefix(`/meet/`)"
      entryPoints: [websecure]
      tls: {}
      service: backend
      middlewares: [meet-headers, security-headers]

The order in middlewares matters, and it is the opposite of what it looks like. The first middleware in the list modifies the response last, so its values win. In our test, with [security-headers, embed-headers], all three paths got the default values; with the override first, as above:

Path What changes
/ The default values
/embed/ frame-ancestors 'self' https://partner.example, and no X-Frame-Options
/reset/ Referrer-Policy: no-referrer
/meet/ camera=(self), microphone=(self)

The 404 pages under /embed/ and /reset/ got the same values as the pages, and the other headers stayed in place on each path. An empty value in customResponseHeaders removes the header, which is how /embed/ drops X-Frame-Options.

Step 4: hide the application’s version

Traefik sends no Server header of its own, but it passes on the application’s. Behind Traefik, our Nginx containers answered with Server: nginx/1.30.6, and WebSec0 removes 5 points from the headers grade when the Server header contains a version (see the Server header guide). Remove it in the same middleware:

YAML
http:
  middlewares:
    security-headers:
      headers:
        # ...the six options above...
        customResponseHeaders:
          Server: ""

With labels:

YAML
      - "traefik.http.middlewares.security-headers.headers.customResponseHeaders.Server="

Our test then returned no Server header at all, on pages and 404s, with the file provider and with labels. Hiding the version in the application, with server_tokens off; for Nginx for example, works too.

Verify it

Check that each header appears exactly once on a page, an error page and a static file. Use your own URLs:

Shell
for url in https://example.com/ https://example.com/does-not-exist https://example.com/assets/app.js; do
  echo "$url"
  for h in content-security-policy strict-transport-security x-frame-options referrer-policy permissions-policy x-content-type-options; do
    printf '  %-26s %s\n' "$h" "$(curl -sI "$url" | grep -ci "^$h:")"
  done
done

Every count should be 1. A 0 everywhere points to a router that does not list the middleware, or to a dynamic file Traefik rejected. Then open your pages with the browser console for CSP, Permissions-Policy or MIME errors, and scan the site with WebSec0.

How WebSec0 grades this configuration

The six headers make up the 100 points of the WebSec0 headers grade. With the middleware above, each one passes:

Header Points Passes when
Content-Security-Policy 25 No 'unsafe-inline' in script-src, or in default-src without script-src
Strict-Transport-Security 20 max-age of at least one year with includeSubDomains
X-Frame-Options 15 DENY or SAMEORIGIN, or frame-ancestors in the CSP
Referrer-Policy 15 The applied value is not unsafe-url or no-referrer-when-downgrade
Permissions-Policy 15 It parses and disables at least one sensitive feature with ()
X-Content-Type-Options 10 The first value is nosniff

A headers grade of A+ starts at 95. The score can also change with other headers: −5 for a version in the Server header (step 4), penalties for cookies without secure attributes (−5 per cookie without Secure, −10 at most; −3 per cookie without SameSite; −3 per session cookie without HttpOnly), and −10 for Access-Control-Allow-Origin: *. Cross-origin isolation headers add bonus points: +5 for Cross-Origin-Opener-Policy: same-origin, +3 for Cross-Origin-Embedder-Policy and +2 for Cross-Origin-Resource-Policy.

The HSTS options also count for the TLS grade: a configuration that would earn an A+ is held at A unless HSTS has a max-age of at least one year and includeSubDomains.

Troubleshooting

Symptom Likely cause Fix
No security headers at all No router lists the middleware Add it to each HTTPS router’s middlewares, or to the entry point.
Every router in a file answers 404 An option the version does not know made Traefik reject the file Check the logs for field not found.
A per-path value is ignored The override middleware is listed after security-headers, or the middleware is on the entry point List the override first, and attach security-headers to routers.
X-Frame-Options still sent on a path The override sets the CSP but does not remove the header Add X-Frame-Options: "" under customResponseHeaders.
No HSTS behind a load balancer The request reaches Traefik over plain HTTP Add forceSTSHeader: true, as the HSTS guide for Traefik explains.
Server shows the application’s version Traefik passes on the application’s Server header Add Server: "" under customResponseHeaders.
Scripts or styles stop loading The CSP or nosniff Check the browser console; start the CSP in report-only mode and fix MIME types.

One guide per header

Every Traefik guide

Other web servers

Security headers on other servers

Questions

Frequently asked questions

Which security headers should Traefik send?

The six that WebSec0 grades: Content-Security-Policy, Strict-Transport-Security, X-Frame-Options, Referrer-Policy, Permissions-Policy and X-Content-Type-Options. One headers middleware sets all of them.

How do I add security headers to every router in Traefik?

List the middleware in each router's middlewares, or attach it to the HTTPS entry point in the static configuration. The entry point is simpler, but per-path values on routers then have no effect.

Does Traefik keep the application's security headers?

No. For the headers the middleware sets, Traefik replaces the application's value. In our test, each header appeared once, with the middleware's value, on the application's pages and 404s.

How do I use different security headers for one path in Traefik?

Add a router with a PathPrefix rule and a middleware with the new values, and list it before security-headers in that router's middlewares. The first middleware in the list writes the response headers last.

How do I remove a header such as X-Frame-Options in Traefik?

Give it an empty value in customResponseHeaders, for example X-Frame-Options: "". Traefik then removes the header from the response, including on error pages.

How do I hide the Server header in Traefik?

Traefik sends no Server header of its own but passes on the application's. Add Server: "" under customResponseHeaders in the same middleware to remove it.

References

Sources

About the author

Portrait of Joshua Martinelle

Security engineer at Tenable

Security engineer at Tenable and web security researcher. He has disclosed more than 60 CVEs since 2020 and builds WebSec0.

Verify the change

Deployed it? Check it.

WebSec0 grades your TLS setup and all six security headers in a few seconds. Free, no account.

Scan your site