Skip to content

WordPress security headers: HSTS, X-Frame-Options and a CSP that survives the block editor

The four set-once security headers you can ship on WordPress in an afternoon, then the Content-Security-Policy rollout that does not break Gutenberg — report-only first, nonces instead of unsafe-inline, and the layer rules that make headers disappear without an error.

Four of the headers people mean by “WordPress security headers” are set-once: Strict-Transport-Security, X-Frame-Options, Referrer-Policy and X-Content-Type-Options take one value each, break nothing on a normal site, and ship in an afternoon. The fifth, Content-Security-Policy, is the only hard one, because WordPress core, your theme and most of your plugins emit inline <script> tags that a policy worth having has to refuse. The route that survives a real site is Content-Security-Policy-Report-Only first, two weeks of violation reports, then enforcement — and exactly one configuration layer per header, because a header written in two places is a header you no longer control.

What you’ll accomplish

  • Ship the four set-once headers at a single layer and prove each arrives exactly once, on pages and on static assets.
  • Settle which of Apache, Nginx, PHP or the CDN actually writes each header, and know which of X-Frame-Options and frame-ancestors browsers obey when both are present.
  • Stand up a report-only CSP with a report collector inside WordPress, and rank the violations it produces.
  • Replace 'unsafe-inline' in script-src with per-request nonces using WordPress’s own script attribute filters — or decide, on evidence, that this site should not.
  • Recognise the three ways a correctly written header vanishes before the browser sees it, none of which log an error.

Prerequisites

  • WordPress 6.x. The script attribute filters used below landed in 5.7; the block editor behaviour described is 6.x.
  • Apache with mod_headers enabled (the cPanel and LiteSpeed case, where .htaccess works), or Nginx where you can edit the server block, or at minimum a writable mu-plugins directory.
  • TLS working end to end, on the canonical hostname and every subdomain you might ever put under includeSubDomains. HSTS before that is a footgun: the browser refuses to fall back to HTTP for the whole max-age, and you cannot reach the visitor to tell them otherwise.
  • The origin IP, if Cloudflare or another proxy sits in front: it is a header-writing layer too, and step 3 reaches past it.
  • A staging copy where you can log in and open the block editor. Every CSP mistake here shows up there first.

How it works

A response header can be attached at any point between PHP and the browser, and each layer outward can add to, replace, or remove what the previous one wrote. There is no error when it happens — the header simply is not on the wire. The layer you pick also decides which requests get the header at all, because a front-end page, a wp-admin screen, a REST call and a .js file take four different paths through the stack.

Matrix of the four layers that can write a security header on WordPress — PHP send_headers, .htaccess mod_headers, the server vhost, a CDN — against four request types, showing PHP covering only front-end pages while outer layers cover everything

Three layer rules account for nearly every “I set the header and it is not there” ticket.

In WordPress, the send_headers action fires from WP::send_headers(), called during WP::main(). That covers front-end page requests and nothing else: wp-admin never calls WP::main(), REST requests are short-circuited on parse_request before send_headers runs, and static files never touch PHP. A header set only in PHP is missing from your admin, your REST API and every .js and .css file on the site.

In Apache, Header always set NAME value replaces any existing value, including one PHP already set, because mod_headers runs in the output filter chain after the handler. Header always add appends a second copy instead, which is almost never what you want for a security header. When PHP should win, Header always setifempty writes the value only if the header is absent.

In Nginx, add_header directives are inherited from the enclosing block only when the current block declares no add_header of its own. A location ~* \.(js|css)$ block adding a single cache header silently drops every security header defined at server level. And add_header genuinely adds: it does not replace a header that came from PHP through FastCGI, so a CSP set in both places sends two Content-Security-Policy headers, which browsers enforce as the intersection of both. That is usually a broken site rather than a stricter one.

Step-by-step

1. Confirm TLS is complete before you touch HSTS. List the hostnames that resolve to this site and check each one answers on HTTPS with a valid certificate.

for h in example.com www.example.com cdn.example.com staging.example.com; do
  printf '%s ' "$h"
  curl -sS -o /dev/null -w '%{http_code} %{ssl_verify_result}\n' "https://$h/" || echo unreachable
done
example.com 200 0
www.example.com 301 0
cdn.example.com 200 0
staging.example.com 000 unreachable

An ssl_verify_result of 0 means the chain verified. Anything else, or an unreachable host, is a subdomain you must not cover yet. Fix it or leave includeSubDomains off for now.

2. Ship the four set-once headers at the outermost layer you control. On Apache or LiteSpeed, put this in the docroot .htaccess outside the # BEGIN WordPress block — WordPress rewrites the contents of that block whenever permalinks are saved, and anything you added inside it disappears.

<IfModule mod_headers.c>
    Header always set Strict-Transport-Security "max-age=86400"
    Header always set X-Content-Type-Options "nosniff"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    Header always set X-Frame-Options "SAMEORIGIN"
</IfModule>

The Nginx equivalent goes in the server block, and must be repeated verbatim inside any location block that declares an add_header of its own:

add_header Strict-Transport-Security "max-age=86400" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header X-Frame-Options "SAMEORIGIN" always;

Note the deliberately short max-age of one day. Run it a week, confirm nothing broke, then raise it to 31536000 — and only then consider includeSubDomains. The longer path is covered in deploying HSTS without painting yourself into a corner.

If you have neither .htaccess nor the server block, send_headers will cover front-end pages:

<?php
// wp-content/mu-plugins/security-headers.php
add_action( 'send_headers', function ( $wp ) {
    header( 'X-Content-Type-Options: nosniff' );
    header( 'Referrer-Policy: strict-origin-when-cross-origin' );
    header( 'X-Frame-Options: SAMEORIGIN' );
} );

Reload once, then check the wire:

curl -sS -o /dev/null -D - https://example.com/ | grep -iE 'strict-transport|x-frame|referrer-policy|x-content-type'
strict-transport-security: max-age=86400
x-content-type-options: nosniff
referrer-policy: strict-origin-when-cross-origin
x-frame-options: SAMEORIGIN

3. Find out what the edge does to that set before you trust the origin. If Cloudflare, a load balancer or any other proxy answers for the hostname, it has the last word. Compare what the origin sends against what a visitor receives:

ORIGIN=203.0.113.10
FILTER='^(strict-transport|x-frame|referrer-policy|x-content-type|content-security)'
diff <(curl -sS -k -o /dev/null -D - --resolve "example.com:443:$ORIGIN" https://example.com/ \
        | tr 'A-Z' 'a-z' | grep -E "$FILTER") \
     <(curl -sS -o /dev/null -D - https://example.com/ | tr 'A-Z' 'a-z' | grep -E "$FILTER")
> strict-transport-security: max-age=31536000

No output at all is the success signal: both sides sent the same set, and the origin is the only layer writing these headers. The line above is the other outcome — a > prefix means the edge added that header itself, a < prefix means it stripped one the origin sent. On Cloudflare the usual sources are a Transform Rule of type “Modify Response Header” and the HSTS panel under SSL/TLS, whose max-age replaces whatever the origin sent. That is how a one-day rollout quietly becomes a one-year commitment. Pick the layer that owns the set and delete the duplicate.

4. Know which of X-Frame-Options and frame-ancestors wins. When a response carries both, browsers obey the CSP frame-ancestors directive and ignore X-Frame-Options entirely. Keeping X-Frame-Options is worth it for very old clients, but from the moment CSP ships, frame-ancestors 'self' decides framing. If a payment provider legitimately frames your site, name its origin in frame-ancestors rather than reaching for ALLOWALL, which is not a valid X-Frame-Options value in the first place.

5. Stand up a report collector before the policy. A report-only policy with nowhere to report does nothing at all.

<?php
// wp-content/mu-plugins/csp-report-collector.php
add_action( 'rest_api_init', function () {
    register_rest_route( 'csp/v1', '/report', array(
        'methods'             => 'POST',
        'permission_callback' => '__return_true',
        'callback'            => function () {
            $body = file_get_contents( 'php://input' );
            if ( $body && strlen( $body ) < 8192 ) {
                error_log( 'CSPREPORT ' . $body );
            }
            return new WP_REST_Response( null, 204 );
        },
    ) );
} );

Browsers post these with Content-Type: application/csp-report or application/reports+json, neither of which WordPress parses, so the body is read straight from php://input. The length cap keeps a hostile client from filling your log, and permalinks must be on for /wp-json/ to route. Confirm the endpoint answers:

curl -sS -o /dev/null -w '%{http_code}\n' -X POST \
  -H 'Content-Type: application/csp-report' \
  -d '{"csp-report":{"blocked-uri":"https://test.invalid/x.js"}}' \
  https://example.com/wp-json/csp/v1/report
204

6. Deploy the policy in report-only mode. This blocks nothing. It is the only safe first policy, and the state machine below is the whole rollout.

The CSP rollout as a state machine — no policy, report-only, analyse violations, enforce — with a loop back from analysis and a rollback edge from enforce

Header always set Reporting-Endpoints "csp-endpoint=\"https://example.com/wp-json/csp/v1/report\""
Header always set Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; report-uri /wp-json/csp/v1/report; report-to csp-endpoint"

report-uri is deprecated but still the only mechanism some browsers implement; report-to with Reporting-Endpoints is the current one. Send both.

Two directive choices are deliberate. style-src carries 'unsafe-inline' because block markup emits style= attributes on the front end and there is no practical alternative on WordPress; style injection is a far weaker vector than script injection, so the loss is small. script-src does not carry 'unsafe-inline', even in report-only: that value permits exactly the injected inline script that cross-site scripting delivers, which is the attack CSP exists to stop. It produces a green audit result and close to no defence.

7. Collect for two weeks, then rank what got flagged. Volume is dominated by a handful of sources.

grep -o '"blocked-uri":"[^"]*"' ~/logs/error_log | sort | uniq -c | sort -rn | head -20
   4417 "blocked-uri":"inline"
    902 "blocked-uri":"https://www.googletagmanager.com"
    311 "blocked-uri":"https://fonts.gstatic.com"
     44 "blocked-uri":"eval"
      6 "blocked-uri":"https://tracker.invalid"

Named hosts are a decision each: add legitimate ones to the matching directive (https://www.googletagmanager.com to script-src, https://fonts.gstatic.com to font-src), and treat anything you do not recognise as a finding rather than an allowlist entry. eval means something calls eval or new Function; find the plugin before reaching for 'unsafe-eval'. inline is the real work, and it is step 8.

8. Nonce the inline scripts, or stop here. WordPress emits inline <script> tags from wp_add_inline_script(), wp_localize_script() and the block editor’s bootstrapping. Two filters attach a nonce attribute to each:

<?php
// wp-content/mu-plugins/csp-nonce.php
function sh_csp_nonce() {
    static $nonce;
    if ( ! $nonce ) {
        $nonce = base64_encode( random_bytes( 16 ) );
    }
    return $nonce;
}

add_filter( 'wp_script_attributes', function ( $attr ) {
    $attr['nonce'] = sh_csp_nonce();
    return $attr;
} );

add_filter( 'wp_inline_script_attributes', function ( $attr ) {
    $attr['nonce'] = sh_csp_nonce();
    return $attr;
} );

add_action( 'send_headers', function () {
    header( "Content-Security-Policy-Report-Only: default-src 'self'; "
        . "script-src 'self' 'nonce-" . sh_csp_nonce() . "' 'strict-dynamic'; "
        . "style-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self'; "
        . "frame-ancestors 'self'; report-uri /wp-json/csp/v1/report" );
} );

Now the constraint that decides the shape of the whole deployment: the nonce changes per request, so only PHP can write that header. Remove the Content-Security-Policy-Report-Only line from .htaccess the moment you add this file, or Apache’s Header always set overwrites the PHP value with the stale nonce-free one and every script on the site gets reported. On Nginx, remove the CSP add_header or you send two policies. Because send_headers does not fire in wp-admin, the editor has no policy until you add an admin_init hook doing the same — the right sequence anyway: get the front end enforcing first.

'strict-dynamic' is what makes this survivable: any script the nonce approves may load further scripts, so a plugin injecting its own <script> tag from an approved bundle keeps working without an allowlist entry. Legacy handlers written as onclick= attributes still fail, and those need the plugin fixed, not the policy widened.

What the block editor genuinely needs, once you write a policy for wp-admin, is narrower than its reputation suggests. script-src needs the nonce plus 'strict-dynamic', because the editor bootstraps from inline scripts and then pulls its own packages in. style-src needs 'unsafe-inline', since block styles are injected as inline rules at runtime with no nonce path. img-src needs data: and blob: for media previews and the image block’s crop tool, and connect-src needs 'self' for the REST traffic behind every autosave. 'unsafe-eval' is the directive people add reflexively. Load the editor under report-only and look for blocked-uri: eval: if it never appears, do not add it, and if it does, find the bundle calling eval or new Function first.

9. Enforce. Only after a full week with no new legitimate blocked-uri, rename the header from Content-Security-Policy-Report-Only to Content-Security-Policy. Keep report-uri and report-to — enforcement is when reports become an alerting signal rather than a checklist.

Validate it works

Prove each header arrives exactly once on a page. Use GET with -D - rather than curl -I, because some caches and proxies handle HEAD differently:

curl -sS -o /dev/null -D - https://example.com/ \
  | tr 'A-Z' 'a-z' \
  | grep -E '^(strict-transport-security|content-security-policy[a-z-]*|x-frame-options|referrer-policy|x-content-type-options):' \
  | cut -d: -f1 | sort | uniq -c
   1 content-security-policy
   1 referrer-policy
   1 strict-transport-security
   1 x-content-type-options
   1 x-frame-options

Any count of 2 is two layers writing the same header. Fix that before going further.

Repeat on a static asset, which never goes through PHP and is where the Nginx location inheritance rule bites:

curl -sS -o /dev/null -D - https://example.com/wp-includes/js/jquery/jquery.min.js \
  | grep -icE '^(strict-transport-security|x-content-type-options):'
2

Both should be present. A 0 means a location block or a CDN rule serves that path outside your header configuration.

Finally, log in, open /wp-admin/post-new.php and check the browser console. Under report-only the editor must load and save normally; violation lines there are data, not breakage. Under an enforcing policy, a blank editor canvas or a save that spins forever means the policy blocked a script the editor needs — roll back to report-only and read the reports.

Troubleshooting

The header is set twice. Almost always PHP and the web server both writing it, or a security plugin duplicating the server config. Two Content-Security-Policy headers are enforced as the intersection of both policies, so the site behaves as if the strictest applied alone; two X-Frame-Options headers can cause browsers to ignore both, quietly removing the protection you thought you had. Decide which single layer owns each header, and use Header always setifempty in Apache when PHP’s value should survive.

Headers are on the homepage but missing from /wp-content/uploads/ or your JS. In Nginx, any location block declaring its own add_header inherits none from server. Repeat the full set inside every such block, or put it in one file and include that file in each. On Apache, a .htaccess in the subdirectory does the same to mod_headers directives above it.

The block editor loads blank under script-src. The editor bootstraps from inline scripts, so 'self' alone with no nonce refuses all of them. Roll back to report-only, add the nonce filters from step 8, and re-enforce only once blocked-uri: inline has stopped appearing. Reaching for 'unsafe-inline' to make it load takes the policy back to roughly no protection.

HSTS preload was submitted too early. A subdomain that cannot serve HTTPS becomes unreachable in every browser that shipped the preload list, and unwinding requires serving max-age=0, requesting removal at hstspreload.org, and then waiting for browser release cycles — months, not hours. Treat preload as a one-way door and leave it off until every hostname under the domain is HTTPS-only.

A CDN or proxy is rewriting the set. Re-run the step 3 diff. If the edge owns the headers, configure them there and remove them from the origin; a header you keep re-adding at the origin while the edge overwrites it will never take.

When this is the wrong approach

A site with dozens of third-party embeds you do not control — an ad stack, a tag manager marketing edits directly, three chat widgets — may never converge on a policy. Each new tag is a new blocked-uri, and the allowlist grows until it permits most of the web, at which point it is documentation rather than a control. There, frame-ancestors, object-src 'none' and base-uri 'self' still pay for themselves; the full script-src project does not.

Report-only forever is a legitimate end state. A policy that never blocks still surfaces injected scripts within minutes, which is more than most WordPress sites have, and watching those reports beats an enforcing policy that gets switched off after the first support ticket.

And if the goal is only a grade on a header scanner, say so and set the four easy headers. That is a real improvement, it takes an afternoon, and it needs none of the above. The header set for a general Apache host is covered in security headers on cPanel; the authoritative directive reference is MDN’s Content-Security-Policy page.

Running WordPress that earns real money deserves an operator — Stack Harbor runs that stack under Enterprise WordPress; book an infrastructure consult.