Best way to set security headers for only HTML files

Hi,

I’m setting up a basic static site, so my Caddyfile is pretty small at the moment, simply pointing to a folder with a bunch of html files generated by a static site generator with file_server enabled.

I want to apply Security Headers, which I’ve been able to do successfully following the Caddy docs shown here:

The problem is that the security header example on here (using the header {} block) applies security headers to every single request (including image, js and css files). I’m just wondering what would be the most simple way to only apply the security headers to the HTML files. Bear in mind that the site URL path won’t have .html at the end. Is there a way to apply headers based on mime type? Or is it best to add another section to the Caddyfile which then removes the headers from any request containing a file extension?

Thanks in advance for your help.

There’s no way to match on the response type in this case, so you’ll need to match on the request. You could use a rule like not path *.css *.js *.png *.jpg or something which would apply the headers only when the path isn’t one of those known file types.

You can also consider to develop a handler which checks the response and add the header which you want, something similar like GitHub - caddyserver/replace-response: Caddy module that performs replacements in response bodies .

jm2c

This topic was automatically closed after 30 days. New replies are no longer allowed.