Content-Security-Policy only on content_type text/html.*

If I understand things correctly the Content-Security-Policy HEADER should only be added to the document and not the following requests.

The Content-Security-Policy HEADER could be quite big and is unnecessary to send on every request.

Is it possible to fix this in the caddyfile using a combination of filter + header?

FILTER

filter rule {
    path /
    content_type text/html.*
    search_pattern ...
    replacement ...
}

HEADER

header / {
    Access-Control-Allow-Origin  *
    Access-Control-Allow-Methods "GET, POST, OPTIONS"
    Content-Security-Policy "default-src 'self';"
}

Hi @axelssonHakan, welcome to the Caddy community!

Header size is so tiny as to be negligible.

These two directives do not interact, unfortunately. It’s not possible to use them in this way.

You can, however, use filter to embed the Content Security Policy in HTML documents as a HTML meta tag. Meta tags is how I usually prefer to specify CSP for my sites, so they don’t come down in headers on any request - they’re only relevant to clients which open and parse the HTML anyway.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.