Add Custom Headers to Cloudflare Pages

Cloudflare Pages can add custom response headers from a plain-text _headers file. Put the file in the site’s output directory—the directory deployed by the build, not necessarily the repository root—and commit it with the project.

The headers are applied at build time, so changing the file requires a new deployment.

A complete _headers example

This was the file used for this site when the article was written:

/*
  X-Frame-Options: DENY
  X-Content-Type-Options: nosniff
  Referrer-Policy: no-referrer
  X-XSS-Protection: 1
  Strict-Transport-Security: max-age=31536000; preload

https://website-2021-oct.pages.dev/*
  X-Robots-Tag: noindex

The first block applies security-related headers to every path on the main site. The second keeps the pages.dev deployment out of search results.

Header rules use multi-line blocks. The first line is a URL or pattern, followed by indented header names and values:

[url]
  [header name]: [header value]

Useful header rules

Allow another origin to read a response with CORS:

/*
  Access-Control-Allow-Origin: *

Use * only when a public response genuinely should be readable from any origin.

Keep a Pages subdomain out of search results:

https://example.pages.dev/*
  X-Robots-Tag: noindex

Prevent MIME-type sniffing:

/*
  X-Content-Type-Options: nosniff

Limit referrer information sent with requests:

/*
  Referrer-Policy: no-referrer

Disable selected browser features:

/*
  Permissions-Policy: fullscreen=(), geolocation=()

X-XSS-Protection was commonly recommended when this post was published, but modern browsers have retired or ignored that older XSS filter. For a current site, I would focus on a good Content Security Policy, X-Content-Type-Options, an appropriate referrer policy, and only the permissions the site actually needs.