Why security headers matter
HTTP response headers control how the browser handles a page. Some of them are security instructions: they enforce HTTPS, forbid embedding in foreign pages, limit which scripts may run and prevent the browser from guessing file types. Without them the page is more vulnerable than it needs to be, even if the application itself is flawless.
The headers in detail
- Strict-Transport-Security (HSTS): the browser will only connect over HTTPS from now on. Recommended: max-age=63072000; includeSubDomains; preload.
- Content-Security-Policy (CSP): defines which sources scripts, styles and images may be loaded from. The most effective protection against cross-site scripting, but also the most laborious.
- X-Content-Type-Options: nosniff stops the browser from guessing the content type.
- X-Frame-Options or frame-ancestors in the CSP: prevents clickjacking through embedding in foreign pages.
- Referrer-Policy: limits which parts of the URL are passed on to other sites. Recommended: strict-origin-when-cross-origin.
- Permissions-Policy: disables browser features such as camera, microphone or geolocation the page does not need.
Information that should not leak
Headers such as Server: nginx/1.18.0 or X-Powered-By: PHP/8.1.2 reveal versions that attackers match against known vulnerabilities. They are not a security problem in themselves, but an unnecessary gift. In nginx: server_tokens off; in PHP: expose_php = Off.
Example for nginx
A solid starting point for a typical website:
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;Frequently asked questions
- Will a CSP break my website?
- A CSP that is too strict blocks scripts and styles. Test with Content-Security-Policy-Report-Only first, collect violations and then enforce the policy.
- Is HSTS with a short max-age enough?
- For the rollout, yes. For the browsers' preload list you need at least one year and includeSubDomains.
- Are the headers set by Cloudflare?
- Cloudflare can add them, but it does not replace the configuration at the origin. The checker shows what actually reaches the visitor.