Adding HTTP response headers to a Netlify site

Static hosting does not mean giving up control of HTTP response headers. On Netlify, you can add security and caching headers with either a _headers file or netlify.toml.

The _headers file must end up in the published directory. Static site generators sometimes ignore files beginning with an underscore, so check the generated output rather than assuming it was copied. With Jekyll, you may need to include the file explicitly in _config.yml.

Rules start with a path, followed by the headers for that path. /* applies to the whole site:

/*
  X-Frame-Options: DENY
  X-XSS-Protection: 1; mode=block
  Referrer-Policy: no-referrer
  X-Content-Type-Options: nosniff

The same rules in netlify.toml look like this:

[[headers]]
  for = "/*"
  [headers.values]
    X-Frame-Options = "DENY"
    X-XSS-Protection = "1; mode=block"
    Referrer-Policy = "no-referrer"
    X-Content-Type-Options = "nosniff"

Caching static assets

You can add separate rules for CSS and JavaScript files. This example asks browsers and shared caches to keep them for one week:

[[headers]]
  for = "*.css"
  [headers.values]
    Cache-Control = "max-age=604800, public"

[[headers]]
  for = "*.js"
  [headers.values]
    Cache-Control = "max-age=604800, public"

Or use the equivalent _headers rules:

/*.css
  Cache-Control: public, s-max-age=604800

/*.js
  Cache-Control: public, s-max-age=604800

Long cache lifetimes work best when filenames change with the file contents. Otherwise a visitor may keep an old stylesheet after you deploy an update. Headers are useful, but they are also easy to configure too aggressively; verify the response in your browser’s network panel after deploying.