How to Add Security Headers to a Static Website on Cloudflare Pages

Learn how to add security headers to a static website on Cloudflare Pages. Understand the _headers file, test changes and avoid breaking scripts or embeds.
What are HTTP security headers?
HTTP response headers let a server communicate security-related instructions to browsers. Depending on the application, useful headers can help control content loading, reduce MIME-type confusion, limit referrer information and enforce HTTPS. Headers are defense in depth; they do not replace secure coding, access control or dependency maintenance.
How Cloudflare Pages reads _headers
Cloudflare Pages supports a plain-text file named _headers in the static asset directory. Rules associate a URL pattern with one or more response headers. Place the file where it is included in the deployed output. Cloudflare documents syntax, rule limits and important exceptions in its Pages headers guide.
Start with a measured policy
Do not copy a large security-header template blindly. Inventory the resources your site loads: scripts, stylesheets, images, fonts, APIs, analytics and embedded content. Add policies that match the actual architecture. A Content Security Policy that blocks a required script can break navigation or application features.
Test Content Security Policy first
Where possible, begin with Content-Security-Policy-Report-Only to observe violations without enforcing the policy. Review browser developer-console messages and adjust the policy deliberately. When the policy is stable, move to the enforcing Content-Security-Policy header. MDN recommends testing a strict policy and resolving resource violations rather than relying on an overly broad allowlist.
Example _headers structure
The following is only a starting illustration. Confirm the values against your own site before deployment:
/*
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
X-Frame-Options: SAMEORIGIN
Add other headers only after checking their browser behavior and compatibility with your application. HSTS, CSP and Permissions-Policy require particular care.
Important Cloudflare Pages limitations
Cloudflare notes that _headers rules apply to static asset responses and are not applied to responses generated by Pages Functions. If a request is handled by a Function or Worker, attach the required headers in that response instead. Test the deployed response, not just the source file, because build output and routing determine what is actually served.
Verify after deployment
Use browser developer tools or an HTTP header inspection command to check the actual response for the homepage and important routes. Test navigation, forms, embedded content and any third-party integrations. Keep a record of the policy and roll back a change if it blocks legitimate functionality.