Traefik guide · Content-Security-Policy

How to set Content-Security-Policy on Traefik

Add a Content-Security-Policy header in Traefik with the headers middleware, in Docker labels or a dynamic file, test it in report-only mode and override it per path.

  • By
  • Updated
  • 4 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'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'

Present on error pages too

In short4 points
  • Define a headers middleware with contentSecurityPolicy, then attach it to each router. A middleware that no router uses sends nothing.
  • Traefik replaces the policy your application sends, and adds it to the application's 404s and to its own 504s. Its own 404, for a host no router matches, gets no header.
  • For report-only mode, use customResponseHeaders. Traefik 2.11 rejects contentSecurityPolicyReportOnly, and one unknown option makes it drop the whole configuration file.
  • For a different policy on one path, add a router with a PathPrefix rule and its own middleware. Do not also attach the site-wide middleware to the entry point: it runs last and overwrites the path's policy.

The short answer

Define a headers middleware with the policy and attach it to the router of your site. 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"

With the file provider, 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"

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

Every snippet below was run on Traefik 2.11, 3.6 and 3.7, in front of an Nginx container, and checked with curl on a page, a 404 and a failing backend.

If you have not chosen a policy yet, read what each CSP directive does first. The policy above suits a site that loads everything from its own domain and has no inline scripts.

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 the labels of your containers:

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

In YAML, wrap the policy in double quotes and keep the single quotes around keywords like 'self'. In Docker Compose, quote the whole label, as above.

Step 1: ship the policy in report-only mode

Report-only mode applies the policy without blocking anything. Pair it with a Reporting-Endpoints header. Set both with customResponseHeaders, which works on every version:

YAML
http:
  middlewares:
    security-headers:
      headers:
        customResponseHeaders:
          Content-Security-Policy-Report-Only: "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'; report-to csp-endpoint; report-uri https://example.com/csp-reports"
          Reporting-Endpoints: 'csp-endpoint="https://example.com/csp-reports"'

Traefik 3.6 and 3.7 also have a contentSecurityPolicyReportOnly option. Traefik 2.11 does not, and the result is worse than an ignored line. In our test it logged field not found, node: contentSecurityPolicyReportOnly and dropped the whole file: every router defined in it answered 404. Check the Traefik logs after each change.

report-to sends reports through the Reporting API; keep report-uri as a fallback for older browsers. Browse your main pages with the developer console open, fix what is reported, and let real traffic run against the policy for a few days.

Step 2: which responses get the header

The middleware acts on everything that goes through the router. In our test:

Response Header
A page from the application Present
A 404 from the application Present
A 504 from Traefik when the application did not answer Present
A page where the application sends its own CSP Present, and the application’s value is replaced
A 404 from Traefik for a host no router matches Absent

The last case has an empty body, so it is harmless. Unlike Nginx and Apache, there is no always flag to remember.

To remove a CSP that the application sends, without setting one, give it an empty value:

YAML
http:
  middlewares:
    remove-csp:
      headers:
        customResponseHeaders:
          Content-Security-Policy: ""

Step 3: a different policy for one path

To let a partner frame /embed/, add a router for that path with its own middleware. Traefik gives priority to the longer rule, so it wins for /embed/ URLs:

YAML
http:
  middlewares:
    csp-embed:
      headers:
        contentSecurityPolicy: "default-src 'self'; frame-ancestors 'self' https://partner.example"

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

Our test returned the /embed/ policy for /embed/ and for a 404 under it, and the site-wide policy everywhere else.

You can also attach a middleware to every router of an entry point, in the static configuration:

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

This saves listing it on each router, but it does not mix with per-path policies. Entry point middlewares wrap the router’s, so they modify the response last. In our test, with security-headers on the entry point, /embed/ got the site-wide frame-ancestors 'none' instead of its own policy. Attach the CSP to routers when some paths need a different value.

Step 4: enforce the policy

When the reports have gone quiet, move the policy to contentSecurityPolicy. Keep the reporting directives: they now report blocked resources.

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; report-to csp-endpoint; report-uri https://example.com/csp-reports"
        customResponseHeaders:
          Reporting-Endpoints: 'csp-endpoint="https://example.com/csp-reports"'

Hashes and nonces

A static site cannot use nonces, because the same HTML is served to everyone. List the hash of each inline script instead. The hash covers the exact text between <script> and </script>, whitespace included:

Shell
printf '%s' "console.log('ok')" | openssl sha256 -binary | openssl base64
# z45zR03J8fjhB+XZI75tfFNuEulXqY6Qn0ZMYwFwVws=
YAML
http:
  middlewares:
    security-headers:
      headers:
        contentSecurityPolicy: "script-src 'self' 'sha256-z45zR03J8fjhB+XZI75tfFNuEulXqY6Qn0ZMYwFwVws='; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"

Traefik cannot generate a nonce or write it into the page. For a dynamic site, let the application send its own policy with a fresh nonce, and do not attach a CSP middleware to its router: Traefik would replace the application’s policy.

Verify it

Check the header on a normal page and on an error page:

Shell
curl -sI https://example.com/ | grep -i content-security-policy
curl -sI https://example.com/does-not-exist | grep -i content-security-policy

Count the headers to catch duplicates. The result should be 1:

Shell
curl -sI https://example.com/ | grep -ci '^content-security-policy:'

Then test one URL under each router, and scan the site with WebSec0. The headers report shows the policy it received and whether it passes.

Troubleshooting

Symptom Likely cause Fix
No CSP at all The middleware is defined but no router lists it Add it to the router’s middlewares.
Every router in a file answers 404 An unknown option, such as contentSecurityPolicyReportOnly on 2.11, made Traefik reject the file Check the logs for field not found and use customResponseHeaders.
Per-path policy ignored The site-wide middleware is also attached to the entry point Attach CSP middlewares to routers only.
The application’s own policy disappears A CSP middleware on its router replaces it Remove the middleware from that router if the application owns the policy.
No CSP on a 404 for an unknown host Traefik answers before any router or middleware Expected: the response has no body to protect.
Inline scripts blocked after enforcing No nonce or hash for them Move them to files, or add hashes or application nonces.

Server hub

Every header on Traefik

Other web servers

Content-Security-Policy on other servers

Questions

Frequently asked questions

How do I add a Content-Security-Policy header in Traefik?

Create a headers middleware with the contentSecurityPolicy option, in Docker labels or a dynamic configuration file, and list it in the router's middlewares. Traefik then sets the header on every response of that router.

Does Traefik keep the CSP my application sends?

Not when the middleware sets one. In our tests, contentSecurityPolicy and customResponseHeaders both replaced the application's policy, so the response carried a single header.

Can I set Content-Security-Policy-Report-Only in Traefik?

Yes. customResponseHeaders works on every version we tested. Traefik 3.6 and 3.7 also accept contentSecurityPolicyReportOnly, but Traefik 2.11 does not, and it then rejects the whole file.

Can I apply the CSP to every router at once?

Yes, by listing the middleware under the entry point's http.middlewares in the static configuration. It then applies to every router on that entry point and overrides any router-level CSP, so per-path policies stop working.

How do I remove the CSP my application sends?

Set it to an empty value in customResponseHeaders: Content-Security-Policy: "". Traefik then removes the header from the response.

References

Sources

  1. Headers middlewareTraefik Labs

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 security headers, including Content-Security-Policy, in a few seconds. Free, no account.

Scan your site