HTTP Security Headers: A Practical 2026 Guide
Configure modern HTTP security headers correctly: CSP, HSTS, framing protection, nosniff, Referrer-Policy, Permissions-Policy, cross-origin isolation, cookies and caching.

HTTP security headers are one of the cheapest forms of defence-in-depth available to a web application. A response header cannot repair broken authorization, parameterized-query mistakes or unsafe server-side code, but it can tell the browser to enforce useful security boundaries around the page it is about to run.
The important word is boundaries. Security headers are not a scorecard where adding more headers automatically makes a site safer. Some are broadly useful, some only make sense for browser-rendered documents, some can break legitimate integrations, and several headers still found in old checklists are obsolete.
This guide focuses on the headers that matter on the modern web, what each one actually protects, and the decisions you should make before deploying it.
Start with a sensible baseline
For a conventional HTTPS website that does not need to be embedded by other origins, a baseline might look roughly like this:
Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
That is an example, not a paste-ready universal policy. Your CSP will depend on the scripts, APIs, images, fonts and frames your application genuinely uses. HSTS requires an HTTPS-only deployment strategy. A Permissions Policy should reflect the browser capabilities your product actually needs.
The right process is therefore:
- understand the threat a header addresses;
- determine whether the browser feature applies to your application;
- configure the narrowest policy that still permits intended behaviour;
- test representative routes and integrations;
- monitor the result after deployment.
See what your site is actually sending
A header policy is only useful if it reaches the browser. Inspect the live response rather than trusting a config file.
1. Content-Security-Policy: control what a document may execute and load
Content Security Policy is the most capable browser security header in this list and also the easiest to get badly wrong.
CSP can constrain where scripts, styles, images, fonts, frames and network connections come from. More importantly, a modern strict CSP can control which scripts are trusted using nonces or hashes rather than merely maintaining a long list of approved hosts.
A deliberately restrictive starting point might be:
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'
But do not conclude that a host allowlist makes XSS impossible. If an allowed origin serves unsafe JSONP, user-controlled JavaScript or another exploitable resource, an attacker may still find a path through the policy. Nonce/hash-based strict policies are generally a stronger model for applications that can support them.
For example:
Content-Security-Policy: script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
The server generates a cryptographically strong unpredictable nonce for the response and places the same value on scripts it intentionally authorizes:
<script nonce="{RANDOM}" src="/assets/app.js"></script>
Generate a fresh nonce for each response. Do not hard-code one into your application bundle or reuse a static value across requests.
Use Report-Only before enforcing a new CSP
A restrictive CSP can break analytics, checkout providers, authentication widgets, maps, chat systems and application code. On an existing site, first observe a candidate policy with:
Content-Security-Policy-Report-Only: ...
Then exercise real routes, inspect browser violations, classify legitimate dependencies and tighten the policy deliberately. Do not respond to every violation by adding another wildcard.
Our CSP series goes into nonces, hashes, strict-dynamic, reporting, frameworks, Trusted Types and production troubleshooting in detail.
2. HSTS: make HTTPS sticky
Strict-Transport-Security tells a browser that has received the policy to use HTTPS for the host for a specified period.
Strict-Transport-Security: max-age=31536000
This protects against scenarios where a user follows or types an http:// URL and an attacker on the network tries to interfere before the browser reaches HTTPS.
There is an important bootstrap limitation: a browser must first receive HSTS over a valid HTTPS connection unless the domain is already on a browser’s HSTS preload list.
includeSubDomains is a commitment
You will often see:
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Do not copy that merely because a scanner awards more points for it.
includeSubDomains means the policy also applies below the hostname. Before enabling it, confirm that every relevant subdomain can remain HTTPS-capable for the policy lifetime. Forgotten legacy services, development hosts and third-party delegated subdomains can otherwise become inaccessible to browsers that have cached the policy.
preload is an even stronger operational commitment. Browser preload programmes have eligibility requirements, and removal is not an instant emergency switch. Treat preload as an explicit infrastructure decision, not a decorative directive.
A sensible rollout is to start with a short max-age, verify production, increase it gradually, then consider subdomains and preload only after you understand the consequences.
3. X-Content-Type-Options: nosniff
This is one of the easiest recommendations in the guide:
X-Content-Type-Options: nosniff
It tells browsers not to reinterpret certain resources as a different MIME type from the one declared by the server.
That makes correct Content-Type headers more important, not less. If your server accidentally serves JavaScript as text/plain, nosniff may cause the browser to reject it. The fix is to correct the MIME type rather than remove the protection.
For user-uploaded files, MIME handling deserves particular attention. Do not assume a filename extension proves what a file contains.
4. Clickjacking: prefer CSP frame-ancestors
Clickjacking places a target application inside a frame and tricks the victim into interacting with it through misleading visual layers.
The older defence is:
X-Frame-Options: DENY
or:
X-Frame-Options: SAMEORIGIN
Modern applications should generally express framing policy through CSP instead:
Content-Security-Policy: frame-ancestors 'none'
or, when same-origin framing is intentional:
Content-Security-Policy: frame-ancestors 'self'
frame-ancestors is more flexible and is the modern mechanism. X-Frame-Options is still commonly sent as a compatibility layer, but avoid inventing unsupported values such as ALLOW-FROM and assuming modern browsers will honour them.
Also distinguish who may frame your page from which frames your page may load. CSP frame-ancestors controls the former; frame-src controls the latter.
If your product is deliberately embeddable — a payment widget, dashboard component or partner portal, for example — blanket DENY is not an appropriate design. Define the intended embedding origins instead.
5. Referrer-Policy: decide what destination sites learn
When a browser navigates or requests resources, it can send a Referer header identifying the page that initiated the request. A referrer policy controls how much of that information is exposed.
A strong general-purpose default is:
Referrer-Policy: strict-origin-when-cross-origin
With that policy, same-origin requests can receive the full referrer URL, while cross-origin requests normally receive only the origin, and referrer information is withheld on HTTPS-to-HTTP downgrade navigation.
You can choose stricter behaviour:
Referrer-Policy: no-referrer
but understand the product impact. Referrer information can be useful for analytics, attribution and debugging.
Most importantly, do not put secrets in URLs in the first place. A restrictive referrer policy is defence-in-depth; it is not permission to place session tokens, passwords or sensitive personal data in query strings.
6. Permissions-Policy: disable browser capabilities you do not need
Permissions Policy controls access to selected browser features, including capabilities such as camera, microphone and geolocation.
A site that needs none of them could explicitly disable them:
Permissions-Policy: camera=(), microphone=(), geolocation=()
An application that embeds a trusted origin and intentionally delegates a capability needs a more specific policy instead.
This header is useful for reducing unnecessary capability, particularly when pages contain third-party frames. But it is not a generic list to copy from somebody else’s security blog. If your video-call application disables its own microphone and camera, the header is technically strict and operationally useless.
Test the actual features your application uses, including embedded content.
7. Cookies are not a header checklist footnote
Set-Cookie is not normally labelled an HTTP security header, but cookie attributes are central to browser security.
A session cookie will commonly need a shape such as:
Set-Cookie: session=...; Path=/; Secure; HttpOnly; SameSite=Lax
The attributes solve different problems:
Securerestricts transmission to secure connections;HttpOnlyprevents JavaScript from reading the cookie throughdocument.cookie;SameSitecontrols when the browser includes it in cross-site requests.
SameSite=Lax is a useful default for many first-party sessions, but authentication protocols, embedded applications and genuinely cross-site workflows can require different behaviour. Cookies using SameSite=None must be Secure in modern browsers.
Do not set SameSite=Strict everywhere without testing sign-in links, payment returns and other cross-site navigation flows.
Cookie prefixes such as __Host- can add useful constraints for high-value cookies. A __Host- cookie must be Secure, use Path=/, and not specify a Domain, which helps prevent subdomains from overriding it.
8. Cache-Control is a security decision for sensitive responses
Authenticated HTML, account exports and API responses can contain information you do not want stored in browser or shared intermediary caches.
For a response that should not be stored:
Cache-Control: no-store
Be precise about terminology: no-cache does not mean “do not cache.” It permits storage but requires revalidation before reuse. no-store is the directive for preventing HTTP caches from storing the response.
Do not disable caching globally as a reflex. Static hashed JavaScript, CSS, images and fonts should usually be cached aggressively. Apply restrictive caching where the sensitivity of the response requires it.
9. Cross-origin isolation headers are powerful — and easy to break things with
Three similarly named headers solve related but different problems:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Resource-Policy: same-origin
COOP
Cross-Origin-Opener-Policy controls whether a top-level document shares a browsing context group with cross-origin documents. Strong isolation can affect opener relationships and popup-based integrations.
COEP
Cross-Origin-Embedder-Policy can require cross-origin resources loaded by the document to explicitly opt in through CORS or CORP. This is part of the setup required for cross-origin isolation and APIs such as SharedArrayBuffer in relevant contexts.
It can also break third-party images, scripts, frames and other resources that do not send compatible headers.
CORP
Cross-Origin-Resource-Policy is sent by a resource to state which origins may load it in certain cross-origin contexts.
These are not baseline headers for every brochure website. Deploy them when your threat model or required browser capability justifies cross-origin isolation, then test popups, authentication, payments, media and third-party resources carefully.
10. CORS headers are access-sharing policy, not generic hardening
You may see this in security-header lists:
Access-Control-Allow-Origin: *
Do not add it because it “looks modern.” CORS response headers deliberately relax the browser’s same-origin restrictions for eligible cross-origin reads.
A public unauthenticated resource may legitimately allow every origin. A private API generally needs a much narrower policy.
If credentials are involved, the rules become stricter and a wildcard origin cannot simply be combined with credentialed browser requests. Validate origins against an explicit allowlist rather than reflecting arbitrary Origin values back to the caller.
CORS is also not authentication. A non-browser client is not prevented from calling your server merely because the server lacks an Access-Control-Allow-Origin header. Enforce authorization on the server.
Headers you should stop adding from old checklists
Security advice has a long half-life. Configuration snippets survive years after browser behaviour changes.
X-XSS-Protection
Do not rely on the old browser XSS auditor. Current guidance is to use a strong CSP and either omit X-XSS-Protection or explicitly disable it where desired:
X-XSS-Protection: 0
Expect-CT
Expect-CT is obsolete for modern deployments. Certificate Transparency requirements moved into browser/platform policy. Remove it rather than treating it as a current hardening control.
HTTP Public Key Pinning
Public-Key-Pins (HPKP) is dead and should not be deployed. Its operational failure modes were severe enough that modern browsers removed support.
Feature-Policy
The old Feature Policy mechanism was replaced by Permissions Policy. Use current Permissions-Policy syntax and check browser support for the individual feature you intend to control.
block-all-mixed-content
If you encounter block-all-mixed-content in old CSP examples, do not build a new policy around it. The directive is obsolete. Modern mixed-content handling and, where appropriate, upgrade-insecure-requests are the relevant mechanisms.
What about Server and X-Powered-By?
Removing unnecessary implementation detail is reasonable:
X-Powered-By: Express
Server: nginx/1.x.x
Exact version disclosure can make opportunistic fingerprinting easier, so production systems commonly suppress or generalize these headers.
Do not overstate the benefit. An attacker can often infer frameworks and infrastructure in other ways. Hiding X-Powered-By does not turn an unpatched server into a secure one.
Treat information reduction as hygiene, not a substitute for patching.
HTML pages and JSON APIs do not need identical headers
This is an easy way to spot cargo-cult configurations.
A CSP is highly relevant to an HTML document that executes JavaScript and embeds resources. The same CSP attached to a JSON API response consumed by a native client may achieve nothing useful.
Likewise, frame-ancestors protects frameable documents; it is not meaningful protection for every 204 No Content response.
Headers such as HSTS can sensibly be applied at a host or edge level, while document-specific controls should match the response type and application architecture.
Design the policy by security boundary and response class, not by forcing one giant header blob onto every endpoint.
Example: Nginx
A simplified server block might include:
server {
listen 443 ssl;
server_name example.com;
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'" always;
# ...
}
Do not copy the CSP unchanged if the site loads resources from other origins. Also understand your server’s header inheritance rules: configuration in nested locations can produce surprising results if you assume a parent header is always inherited.
Example: ASP.NET Core
You can set straightforward response headers in middleware:
app.Use(async (context, next) =>
{
context.Response.OnStarting(() =>
{
context.Response.Headers["X-Content-Type-Options"] = "nosniff";
context.Response.Headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
context.Response.Headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()";
return Task.CompletedTask;
});
await next();
});
HSTS is normally better handled through ASP.NET Core’s HSTS middleware or at a trusted reverse proxy/edge where your HTTPS architecture is known. A nonce-based CSP also needs application-aware generation and HTML integration; it should not be reduced to a static string if your design depends on per-response nonces.
Example: Node/Express
For Express applications, mature middleware such as Helmet can manage a number of these headers and provides safer defaults than repeatedly hand-writing them.
Even with middleware, inspect the emitted headers. Defaults change, applications have exceptions, and a CSP still needs to describe your real resource graph.
Test the browser-visible result
After deployment, inspect the actual response from the public route. Reverse proxies, CDNs, serverless platforms and application middleware can add, remove, merge or override headers.
For example:
curl -I https://example.com/
Then test representative pages, not only /:
curl -I https://example.com/login
curl -I https://example.com/account
curl -I https://example.com/checkout
Use browser developer tools for CSP and CORS behaviour because the browser’s enforcement context matters. Automated browser tests are valuable for critical routes after tightening a policy.
A scanner can tell you that a header is absent or obviously weak. It cannot know that your Permissions-Policy accidentally disabled a legitimate QR scanner, or that COOP broke an authentication popup. Security testing still needs application context.
A practical production checklist
Before calling your header configuration finished, verify that:
- all public application traffic is served over valid HTTPS before committing to long-lived HSTS;
- HSTS subdomain/preload decisions match your real DNS and certificate estate;
- CSP reflects actual resources and has been exercised on important routes;
- framing is explicitly allowed or denied according to the product’s embedding model;
- MIME types are correct and
nosniffis enabled; - referrer behaviour matches your privacy and analytics requirements;
- unnecessary browser capabilities are disabled without breaking required features;
- session cookies have appropriate
Secure,HttpOnlyandSameSiteattributes; - sensitive responses have deliberate cache policy;
- CORS is configured only where cross-origin browser access is intended;
- obsolete headers have not been added simply to satisfy an old checklist;
- the live edge response has been tested after every CDN/proxy layer.
The principle that matters most
A good security-header configuration is not the one with the greatest number of headers. It is the one whose browser-enforced rules accurately describe how the application is supposed to behave.
Start with the broadly useful controls, understand the operational commitment behind HSTS, invest properly in CSP for browser applications, treat cookies and caching as part of the same security boundary, and add cross-origin isolation only when you actually need it.
Most importantly, test what reaches the browser. The configuration sitting in your repository is not the security control; the response the user receives is.
