Skip to content

HTTP Security Headers to Protect Your Website

A guide to HTTP security headers for protecting your site: what each header does (HSTS, CSP, X-Frame-Options, X-Content-Type-Options, Referrer-Policy and Permissions-Policy), the recommended values, and how to add them in Nginx, Apache, Cloudflare and WordPress, with scanning tools, a gradual rollout plan and common mistakes.

Securityخالد الراشد27 min read
Illustration of a response card stacked with protective tags arriving at a browser with a shield, representing HTTP security headers
On this page

What are HTTP security headers, and why do they matter?

Every time a browser requests a page from your server, the server responds in two parts: the response body (the HTML, images and scripts) and the response headers, which are key-value pairs that describe the response and direct the browser's behavior. HTTP security headers are a specific set of these headers that give the browser strict rules: "don't load scripts except from these sources," "don't display my page inside a frame on another site," "talk to me over HTTPS only from now on." The browser is what enforces these rules, so the protection happens on the visitor's device, not just on your server.

Their importance comes from the principle of defense in depth: don't rely on a single layer. You may have an excellent firewall and clean code, but a single XSS vulnerability in a plugin, or a mistake in sanitizing an input, is enough to inject a malicious script. This is where CSP comes in as a final safety net that stops the browser from executing that script in the first place. Security headers don't replace sound code, but they limit the damage when other layers fail, and that is exactly the essence of serious security.

Their extra advantage is that they are very cheap: they don't require rewriting your application, just a few lines in the server configuration that enable protection working in all modern browsers immediately. The following table summarizes the seven essential headers we will detail, and it is your quick reference for the rest of the article:

HeaderPurposeRecommended valueRisk when missing
Strict-Transport-SecurityEnforces HTTPS and prevents falling back to HTTPmax-age=31536000; includeSubDomains; preloadSSL stripping attacks and interception of the first connection
Content-Security-PolicyCurbs script injection and XSSA custom policy with default-src 'self'Injected malicious scripts run unrestricted
X-Frame-OptionsPrevents the site from being shown inside a frameDENY or SAMEORIGINClickjacking attacks
X-Content-Type-OptionsPrevents content type guessingnosniffAn uploaded file is executed as if it were a script
Referrer-PolicyControls the referrer information sentstrict-origin-when-cross-originLeakage of sensitive paths and URLs
Permissions-PolicyRestricts browser permissionsDisable what you don't useAbuse of the camera/location by an injected script
Cross-Origin-* (COOP/COEP/CORP)Isolates windows and resourcesAs needed for sensitive featuresCross-origin leaks (Spectre)
HTTP security headers in the server responseServerAdds the headersBrowserApplies the policiesSecurity response headersHSTS: always enforces HTTPSCSP: restricts content sourcesX-Frame-Options: prevents framingX-Content-Type-Options: nosniffReferrer-Policy + Permissions-PolicyThe server sends the headers with every response; the browser enforces them
HTTP security headers: the server adds them to every response (HSTS, CSP, X-Frame-Options, X-Content-Type-Options, Referrer/Permissions-Policy), and the browser enforces them to protect the visitor.

Before we dive into the details, note that all these headers assume your site already runs on HTTPS. If you haven't enabled a certificate yet, start with the guide installing an SSL certificate and enabling HTTPS, because the HSTS header is meaningless, and even dangerous, on a site that doesn't fully support HTTPS.

HSTS: enforcing HTTPS without compromise

The Strict-Transport-Security header, known as HSTS, is the simplest of the headers and one of the most effective. Its job is to tell the browser that it must communicate with your domain over HTTPS only for a set period, so if someone tries to open http://, the browser automatically switches it to https:// before sending any request over the network.

The problem it solves is the SSL stripping attack: even if your site redirects HTTP to HTTPS with a 301 redirect, the first request goes out over unencrypted HTTP, and a man-in-the-middle attacker can intercept it, block the redirect and keep the victim on an insecure connection. HSTS cuts this off completely, because the browser remembers that it must not touch HTTP for this domain at all. To understand the close relationship between HSTS and the TLS handshake that secures the connection, it helps to picture what happens behind the scenes:

How does the TLS handshake encrypt the connection?Browser (client)Server1 · ClientHello (supported versions and algorithms)2 · ServerHello + certificate + public key3 · Verify the certificate and chain of trust4 · Exchange/derive the session key5 · Fully encrypted connection (HTTPS)
A simplified TLS handshake: exchanging hellos and the certificate, verifying the chain of trust, agreeing on a session key, then full encryption of the data.

The three HSTS parameters

The HSTS header consists of three parts, and understanding them saves you from the most dangerous security mistake: locking your visitors out of your own site.

ParameterFunctionCritical note
max-age=31536000How long to remember, in seconds (here a full year)The browser stores it, so you can't easily roll back
includeSubDomainsApplies the rule to all subdomainsMake sure every subdomain supports HTTPS first
preloadAdds the domain to the browsers' preload listAn almost final decision that is hard to reverse

The recommended value for production:

nginx
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

The preload list and its risks

Normally, the browser learns the HSTS rule after the first successful visit over HTTPS, which leaves a small window on the first visit. The preload list closes this gap: a list maintained by the Chromium project and adopted by the major browsers, containing domains that are treated as HTTPS-only from the very first moment, without any previous visit. To join, you submit your domain at hstspreload.org.

But be careful: inclusion in the list is almost permanent. Removing a domain from it can take months and spreads slowly with browser updates. So don't request preload until you are absolutely sure that your main domain and all its subdomains will stay on HTTPS for years. The classic mistake: a developer adds preload and then discovers that a subdomain (such as legacy.example.com) doesn't support HTTPS, so it becomes permanently unreachable, even from browsers that have loaded the list.

Expert tip: Start with a short max-age (such as 300 seconds = 5 minutes) when you first enable HSTS, check that everything works, then raise it gradually to a year. Don't add includeSubDomains or preload until you have verified every subdomain.

Content-Security-Policy: a shield against XSS

Content-Security-Policy (CSP) is the most powerful and most complex of the headers. It gives the browser an allowlist of the sources that are permitted to load content (scripts, styles, images, fonts, frames...). The browser refuses to load or execute any resource outside the list. So even if an attacker manages to inject <script src="https://evil.com/x.js"> through an XSS vulnerability, the browser refuses to load it because evil.com is not on the allowlist.

The core directives

CSP is made up of directives, and each directive governs one type of resource. The following table covers the most commonly used ones:

DirectiveGovernsExample value
default-srcThe default source for anything not specified'self'
script-srcSources of JavaScript files'self' https://cdn.example.com
style-srcSources of CSS stylesheets'self' 'unsafe-inline'
img-srcImage sources'self' data: https:
font-srcFont sources'self' https://fonts.gstatic.com
connect-srcfetch/XHR/WebSocket destinations'self' https://api.example.com
frame-ancestorsWho is allowed to frame your site'none' or 'self'
base-uriRestricts the <base> tag'self'
form-actionForm submission destinations'self'
object-srcSources for <object>/<embed>'none'
upgrade-insecure-requestsUpgrades HTTP links automatically(no value)

The special keywords go between single quotes: 'self' (the same origin), 'none' (nothing), 'unsafe-inline' (allows inline code; avoid it), 'unsafe-eval' (allows eval; avoid it), and 'nonce-XXX' and 'sha256-XXX' (we explain both below).

An example of a balanced CSP policy

A reasonable starting policy for a typical site:

text
Content-Security-Policy:
  default-src 'self';
  script-src 'self' https://www.googletagmanager.com;
  style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
  img-src 'self' data: https:;
  font-src 'self' https://fonts.gstatic.com;
  connect-src 'self' https://www.google-analytics.com;
  frame-ancestors 'self';
  base-uri 'self';
  form-action 'self';
  object-src 'none';
  upgrade-insecure-requests;

nonce and hash: getting rid of unsafe-inline

The most dangerous compromise in CSP is 'unsafe-inline' in script-src, because it effectively cancels the XSS protection (the attacker injects an inline script and it is allowed). The two clean alternatives:

ApproachHow it worksWhen to use it
nonceA random token generated for each request, placed in the header and in the script tagDynamic content generated by the server
hashA SHA-256 fingerprint of the inline script's content itselfStatic inline scripts that don't change

With a nonce, your server generates a unique random value for each page and places it in the header script-src 'nonce-r4nd0m' and in the script tag <script nonce="r4nd0m">. The attacker doesn't know the random value for the user's request, so they cannot inject an accepted script. This is the gold standard for a modern CSP.

Report-Only mode and violation reports

Here is the most important practical trick: don't enforce CSP right away. Use the Content-Security-Policy-Report-Only header first. In this mode, the browser doesn't block anything; instead it sends a report about everything that would have been blocked to an endpoint you specify. You collect these reports for weeks, discover from them all the legitimate sources you forgot (an ad script, a chat widget, a font CDN...), add them to the allowlist, and then, and only then, switch the header to enforcement mode.

text
Content-Security-Policy-Report-Only:
  default-src 'self';
  script-src 'self';
  report-uri /csp-report-endpoint;
  report-to csp-endpoint;

Expert tip: Never go directly from "no CSP" to "enforced CSP" on a production site. The safe path is always: Report-Only → collect → adjust → enforce. This protects your visitors from a sudden blank white screen.

Clickjacking: X-Frame-Options vs. frame-ancestors

A clickjacking attack loads your site inside a transparent <iframe> on top of a malicious page, so the victim thinks they are clicking an innocent button while they are actually pressing "Confirm transfer" or "Delete account" on your framed site. The defense: tell the browser who is allowed to frame your site.

There are two mechanisms for this, one old and one modern:

AspectX-Frame-OptionsCSP frame-ancestors
StatusOld but widely supportedModern and the recommended standard
ValuesOnly DENY or SAMEORIGINA full list of origins ('none', 'self', specific domains)
Allowing multiple domainsNo (only one domain in the deprecated ALLOW-FROM)Yes (several trusted domains)
Precedence when they conflictThe browser ignores it if frame-ancestors is presentTakes precedence over X-Frame-Options

The recommendation: use both for compatibility with very old browsers, but know that frame-ancestors takes precedence wherever it is supported. To prevent framing entirely:

nginx
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Content-Security-Policy "frame-ancestors 'self'" always;

If you want to prevent framing from any party at all (not even yourself), use DENY and frame-ancestors 'none'. If you need to allow only a specific partner, this is where frame-ancestors 'self' https://partner.example.com wins, because X-Frame-Options doesn't support multiple domains.

X-Content-Type-Options: nosniff

This small header has a single value: nosniff. Its job is to prevent MIME sniffing, that is, guessing the content type. Some older browsers used to "guess" a file's type by inspecting its content instead of relying on the Content-Type header. That is dangerous: an attacker uploads a .jpg image file that actually contains JavaScript code, and the browser guesses it is a script and executes it. With nosniff, the browser sticks strictly to the declared content type and doesn't guess.

nginx
add_header X-Content-Type-Options "nosniff" always;

The value is always nosniff, without exception, and it is a completely safe header that breaks practically nothing, so add it to every site without hesitation. Its only requirement is that the Content-Type headers on your server are correct in the first place.

Referrer-Policy: don't leak your URLs

When a visitor clicks a link that takes them from your page to another site, the browser by default sends a Referer header containing the full address of the page they came from. This can be a serious leak: imagine a link on the page https://app.example.com/reset-password?token=secret123, where the secret token reaches the external site as part of the referrer. Referrer-Policy controls how much information is sent.

ValueBehaviorWhen to use it
no-referrerNever sends the referrerMaximum privacy; may break analytics
same-originSends the referrer to the same origin onlyStrong protection while keeping internal analytics
strict-originSends only the origin (no path), and only over HTTPSA good balance
strict-origin-when-cross-originFull path internally, origin only externallyRecommended for most sites
unsafe-urlAlways sends everythingAvoid it

The recommended value is the default in modern browsers, but it is better to set it explicitly:

nginx
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

Permissions-Policy: reining in browser permissions

It was previously called Feature-Policy and was renamed Permissions-Policy with a change in syntax. Its job is to control the powerful browser features that your page (or any frame inside it) can use: the camera, the microphone, geolocation, motion sensors, payments, full screen... The principle: disable everything you don't use, so if a malicious script is injected, it cannot turn on the camera or read the location.

FeatureDirectiveValue to disable
Cameracameracamera=()
Microphonemicrophonemicrophone=()
Geolocationgeolocationgeolocation=()
Paymentpaymentpayment=()
Full screenfullscreenfullscreen=(self)
Sensorsaccelerometer, gyroscopeaccelerometer=()

The syntax: a comma-separated list, each item feature=(origin list). Empty parentheses () mean fully disabled, and (self) means allowed for your own domain only:

nginx
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), fullscreen=(self)" always;

Disable generously; you can always allow a feature later when you really need it. This is much simpler than tracking every third-party script that might request a permission it doesn't need.

A brief look at COOP, COEP, CORP and CORS

This is the group of cross-origin isolation headers, newer and more specialized, which emerged in response to side-channel attacks such as Spectre. Most sites don't need them, but they are worth knowing:

HeaderFull nameShort description
COOPCross-Origin-Opener-PolicyIsolates your window from windows of other origins
COEPCross-Origin-Embedder-PolicyRequires every embedded resource to explicitly allow being loaded
CORPCross-Origin-Resource-PolicySpecifies who is allowed to fetch your resources
CORSCross-Origin Resource SharingA mechanism that allows controlled cross-origin resource sharing

You need COOP and COEP together (with the values same-origin and require-corp) only if you want to enable features that require cross-origin isolation, such as SharedArrayBuffer or high-precision timing. For a regular blog or store, adding Cross-Origin-Opener-Policy: same-origin as a lightweight extra layer of protection is enough, and you can postpone the rest until you really need them. CORS is a separate topic that governs JavaScript's access to resources on other domains; it has less to do with protecting your site directly than with regulating APIs.

Deprecated headers to avoid

Not all old "security" headers are useful today; some have become harmful or pointless:

HeaderStatusWhy to avoid it
X-XSS-ProtectionDeprecatedThe old XSS filter was removed from browsers and can open vulnerabilities; use CSP instead (or set it to 0)
Expect-CTDeprecatedCertificate Transparency is now mandatory automatically, so it is no longer needed
Public-Key-Pins (HPKP)Deprecated and dangerousKey pinning caused catastrophic outages and was removed from browsers
Feature-PolicyLegacyReplaced by Permissions-Policy with a new syntax

The rule: if you find X-XSS-Protection: 1; mode=block in your old configuration, remove it or set it to 0, and rely on CSP. Never add HPKP: a small mistake in it locks your visitors out of your site for months.

How to add the headers on each server

How you add the headers depends on your setup. The table summarizes the options, and then we detail each one:

EnvironmentWhere to add themImportant note
NginxThe server or http blockUse always so error pages are included
Apache.htaccess or the VirtualHost configurationRequires mod_headers to be enabled
Cloudflare/CDNTransform Rules (Response Headers)Applied at the edge before your server
WordPressA function in functions.php or a pluginBetter at the server level than the application

Nginx

In Nginx, headers are added with the add_header directive. The critical point that many people miss: add the word always at the end of every line, otherwise the headers won't be sent with error responses (404, 500...), which are pages that can also be exploited:

nginx
server {
    # ... rest of the configuration ...

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" 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'; frame-ancestors 'self'; object-src 'none'; base-uri 'self'" always;
}

A crucial warning in Nginx: the add_header directive is not inherited by a child block (such as location) if that block defines its own add_header; in that case all the parent block's headers disappear. If you need headers inside a particular location, redefine all the headers there, or use the headers-more module (more_set_headers), which behaves with different logic. After editing, always check with nginx -t and then reload with nginx -s reload.

Apache (.htaccess)

In Apache, they are added through the mod_headers module with the Header set directive:

apache
<IfModule mod_headers.c>
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set X-Content-Type-Options "nosniff"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    Header always set Permissions-Policy "camera=(), microphone=(), geolocation=()"
    Header always set Content-Security-Policy "default-src 'self'; frame-ancestors 'self'; object-src 'none'; base-uri 'self'"
</IfModule>

Note the word always after Header to make sure the headers are sent even with error pages (the counterpart of always in Nginx). Make sure mod_headers is enabled (on many shared hosts it is enabled by default). Use Header set for the new value and Header unset to remove an unwanted header (useful for deleting the deprecated X-XSS-Protection).

Cloudflare and CDNs

If you are behind Cloudflare or a CDN, you can add the headers at the edge without touching your server. This is convenient, but it can cause duplication (we discuss this under common mistakes). In Cloudflare:

Go to Rules, then Transform Rules, then Modify Response Header, and create a rule that applies to all requests (hostname equals your domain), then add a Set static action for each header with its name and value. Cloudflare applies this to every response passing through its network. The advantage: instant activation at the edge and extra protection alongside the network's other protection layers. To understand how these layers fit together:

Protection layers at the CDN edgeVisitor(or an attack)DDoS protectionWAFEdge cacheHidden originIP not exposedMalicious traffic is blocked at the edge before reaching the server
Edge security: traffic passes through DDoS protection, then the WAF, then the cache, so malicious traffic never reaches the origin hidden behind the CDN.

The only drawback: if your origin server adds the same headers, they appear twice. Choose only one place (the server or the edge) for each header, or enable the "overwrite" option in Cloudflare so it replaces instead of adding.

WordPress

The cleanest way for WordPress is to add them at the server level (Nginx/Apache/CDN), because it is more efficient and covers every request, including static files. But if you have no server access (simple shared hosting), you can do it from functions.php in a child theme:

php
add_action( 'send_headers', function () {
    header( 'X-Frame-Options: SAMEORIGIN' );
    header( 'X-Content-Type-Options: nosniff' );
    header( 'Referrer-Policy: strict-origin-when-cross-origin' );
    header( 'Permissions-Policy: camera=(), microphone=(), geolocation=()' );
    header( "Content-Security-Policy: default-src 'self'; frame-ancestors 'self'; object-src 'none'" );
} );

The drawback of the application approach: it is not applied to static files served directly by the server (images, CSS, JS) or to error pages, and it adds a small load on PHP. That is why adding them on the server always remains the better option. Instead of editing code, there are dedicated plugins for managing headers if you prefer a graphical interface. And in general, WordPress security is broader than headers alone, so see the guide securing a WordPress site to place these headers within a complete protection strategy.

Testing and verifying the headers

After adding them, don't assume success: test. You can start with a free security headers analyzer to measure how complete your site's headers are and highlight what is missing in seconds, then follow up with other free tools that give your site a grade and explain the gaps:

ToolWhat it measuresGrading scale
securityheaders.comPresence and values of the essential security headersA+ to F
Mozilla ObservatoryHeaders + TLS configuration + other practices0 to 100+ and a letter grade
CSP Evaluator (Google)Quality of the CSP policy and detection of its weaknessesDirective-by-directive analysis
Manual check through DevToolsThe actual headers in every responseThe Network tab

For a quick manual check from the command line:

bash
curl -sI https://example.com | grep -i -E 'strict-transport|content-security|x-frame|x-content-type|referrer-policy|permissions-policy'

Don't chase an A+ at any cost; the grade is a means, not an end. A truly strict CSP policy is worth more than a perfect score with 'unsafe-inline' cancelling the protection. Read the details of the report, not just the letter.

A gradual rollout plan

Enabling all the headers at once on a live site is a recipe for breaking it. Follow these stages in order for a safe rollout:

StageActionGoal
1Add the "safe" headers first: nosniff, X-Frame-Options, Referrer-PolicyImmediate gains with no risk of breakage
2Enable HSTS with a short max-age (such as 300)Testing without a long commitment
3Raise max-age to a year once confirmedFull HTTPS enforcement
4Add CSP in Report-Only modeCollect violations without blocking
5Review the reports and adjust the allowlist (weeks)Discover all legitimate sources
6Switch CSP to enforcement modeFull protection
7Tighten gradually (replace unsafe-inline with a nonce)The highest level of security

The governing principle: start with what's safe, defer what's risky, and monitor before enabling HSTS preload and an enforced CSP. This gradual approach turns a daunting task into a series of steps, most of which can be undone.

Common mistakes and how to fix them

Most problems recur in familiar patterns. This table is your reference when something goes wrong:

SymptomLikely causeFix
The site appears unstyled / scripts are brokenA strict CSP blocks legitimate resourcesEnable Report-Only, collect the sources, add them to the list
A header appears twice in the responseAdded by the server and the application/CDN togetherChoose one place or enable overwrite
Headers are missing from 404/500 pagesForgetting always in Nginx/ApacheAdd always to every line
The browser refuses to open the site after HSTSA subdomain without HTTPS, with includeSubDomainsFix HTTPS for the subdomain or remove the directive
Headers are correct in curl but don't work in the browserCDN/browser cachingPurge the CDN cache, test in a private window
Nginx headers disappear inside a particular locationadd_header in the child block overrides the parentRedefine the headers or use headers-more
Analytics/ads stopped workingconnect-src/script-src doesn't include their providerAdd the provider's domain to the right directive

Breaking the site with CSP

This is the most dangerous one: you deploy an enforced CSP and the site's styling disappears or features break because the browser blocked legitimate CSS or JS. Prevention: always Report-Only first. Emergency fix: immediately switch the header to Content-Security-Policy-Report-Only (which stops the blocking) or remove it temporarily, then open the Console in DevTools to read the violation messages carefully. They tell you exactly which resource was blocked and which directive needs adjusting.

Duplicate headers

When your origin server adds a header and Cloudflare adds it too, the browser receives two values. For some headers (such as CSP), the browser may apply the most restrictive one, and others cause unexpected behavior. The rule: one source per header. Decide where you manage the headers (the server or the edge) and stick to it, or enable the replace option in the CDN.

Forgetting error pages

404 and 500 pages are real responses that can be exploited (for example, framed in a clickjacking attack). If you forget always in Nginx or Apache, these pages go out without protection headers. Always verify by requesting a page that doesn't exist and inspecting its headers.

Enabling HSTS too early

Don't enable HSTS, especially with includeSubDomains and preload, before everything is reliably on HTTPS. Enabling it early locks visitors out of any part that doesn't support HTTPS, and rolling back is hard because the browser has stored the rule. Always start with a small max-age. And remember that HSTS is one branch of a broader strategy for resisting attacks, which also includes, for example, DDoS protection at the network level.

Final expert tips

  • Automate, don't rely on memory: put the headers in your infrastructure configuration (IaC) or server template, so they aren't forgotten when a new server is deployed.
  • Monitor continuously: re-test after every major update or when adding a third-party tool; it can suddenly break your CSP.
  • Document your CSP policy: comment on every directive and why each source was added, because a CSP rots quickly without documentation.
  • Don't trust the grade alone: an A+ with 'unsafe-inline' is weaker than a B with a real nonce.
  • Test in a staging environment: try the enforced CSP on staging before production whenever possible.

Security headers are a small investment with a big return: minutes of setup in exchange for a layer of protection that works in every visitor's browser and complements your SSL certificate, firewall and backups to form a complete defense. Start today with the safe headers, then move confidently toward a strict CSP.

Frequently asked questions

Do HTTP security headers replace a firewall and SSL? No. They are a complementary layer within defense in depth, not a replacement. You first need working SSL/HTTPS (see installing an SSL certificate), a firewall, clean code and updates. The headers limit the damage when the other layers fail, especially CSP against XSS.

Which header should I start with if my time is limited? Start with the three safe ones that don't break anything: X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN and Referrer-Policy: strict-origin-when-cross-origin. Add them in minutes, then move on to HSTS and CSP gradually later.

Can enabling CSP break my site? Yes, if it is enforced all at once without testing, it can block legitimate CSS or scripts. That is why you should use Content-Security-Policy-Report-Only first for weeks to collect violations and adjust the allowlist, then switch to enforcement mode safely.

What is the difference between X-Frame-Options and frame-ancestors? Both prevent clickjacking by stopping your site from being framed. X-Frame-Options is older and supports only DENY or SAMEORIGIN, while frame-ancestors (a CSP directive) is modern, supports several trusted domains and takes precedence when they conflict. Use both for maximum compatibility.

Do I need includeSubDomains and preload in HSTS? Not right away. Add includeSubDomains only after making sure all your subdomains support HTTPS, and preload only after a long-term commitment to HTTPS, because removing it from the browsers' list is difficult and very slow.

Why do my headers appear twice? Because they are added from two sources: your origin server and the CDN (such as Cloudflare) together, or the server and the application together. Pick one source for each header, or enable the "overwrite/replace" option in the CDN so it replaces instead of adding.

Is X-XSS-Protection still useful? No. It has become obsolete, its filter has been removed from browsers, and in rare cases it can even open vulnerabilities. Rely on CSP instead, and if you find it in your old configuration, set it to 0 or remove it.

How do I test my headers after adding them? Use securityheaders.com and Mozilla Observatory to get a grade and an explanation, Google CSP Evaluator to assess your CSP policy specifically, or check manually with curl -sI https://yoursite.com or the Network tab in DevTools. Read the details, not just the grade.

Where is the best place to add headers in WordPress? At the server level (Nginx/Apache) or the CDN, because it is more efficient and covers static files and error pages. Adding them through functions.php or a plugin is possible when you have no server access, but it doesn't cover static resources and adds load on PHP.

Should I set the headers on the server or on Cloudflare? Whichever suits your architecture, but choose one for each header to avoid duplication. The edge (Cloudflare Transform Rules) is quicker to enable and applies before your server; the server gives you fine-grained control and works even without a CDN. Don't repeat a header in both places without the replace option.

Do I need COOP, COEP and CORP for my site? Usually not. These are specialized isolation headers that are only required for features such as SharedArrayBuffer or high-precision timing. For most sites, adding Cross-Origin-Opener-Policy: same-origin as a lightweight layer is enough, and you can postpone the rest until a real need for them appears.

Sources

Frequently asked questions

Do HTTP security headers replace a firewall and SSL?

No. They are a complementary layer within defense in depth, not a replacement. You first need working SSL/HTTPS (see installing an SSL certificate), a firewall, clean code and updates. The headers limit the damage when the other layers fail, especially CSP against XSS.

Which header should I start with if my time is limited?

Start with the three safe ones that don't break anything: X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN and Referrer-Policy: strict-origin-when-cross-origin. Add them in minutes, then move on to HSTS and CSP gradually later.

Can enabling CSP break my site?

Yes, if it is enforced all at once without testing, it can block legitimate CSS or scripts. That is why you should use Content-Security-Policy-Report-Only first for weeks to collect violations and adjust the allowlist, then switch to enforcement mode safely.

What is the difference between X-Frame-Options and frame-ancestors?

Both prevent clickjacking by stopping your site from being framed. X-Frame-Options is older and supports only DENY or SAMEORIGIN, while frame-ancestors (a CSP directive) is modern, supports several trusted domains and takes precedence when they conflict. Use both for maximum compatibility.

Do I need includeSubDomains and preload in HSTS?

Not right away. Add includeSubDomains only after making sure all your subdomains support HTTPS, and preload only after a long-term commitment to HTTPS, because removing it from the browsers' list is difficult and very slow.

Why do my headers appear twice?

Because they are added from two sources: your origin server and the CDN (such as Cloudflare) together, or the server and the application together. Pick one source for each header, or enable the "overwrite/replace" option in the CDN so it replaces instead of adding.

Is X-XSS-Protection still useful?

No. It has become obsolete, its filter has been removed from browsers, and in rare cases it can even open vulnerabilities. Rely on CSP instead, and if you find it in your old configuration, set it to 0 or remove it.

How do I test my headers after adding them?

Use securityheaders.com and Mozilla Observatory to get a grade and an explanation, Google CSP Evaluator to assess your CSP policy specifically, or check manually with curl -sI https://yoursite.com or the Network tab in DevTools. Read the details, not just the grade.

Where is the best place to add headers in WordPress?

At the server level (Nginx/Apache) or the CDN, because it is more efficient and covers static files and error pages. Adding them through functions.php or a plugin is possible when you have no server access, but it doesn't cover static resources and adds load on PHP.

Should I set the headers on the server or on Cloudflare?

Whichever suits your architecture, but choose one for each header to avoid duplication. The edge (Cloudflare Transform Rules) is quicker to enable and applies before your server; the server gives you fine-grained control and works even without a CDN. Don't repeat a header in both places without the replace option.

Do I need COOP, COEP and CORP for my site?

Usually not. These are specialized isolation headers that are only required for features such as SharedArrayBuffer or high-precision timing. For most sites, adding Cross-Origin-Opener-Policy: same-origin as a lightweight layer is enough, and you can postpone the rest until a real need for them appears.