Configure Content Security Policy Headers for WordPress

Configure a Content Security Policy for WordPress

A Content Security Policy (CSP) header tells the browser which sources a page may load scripts, styles, images, fonts and frames from, and whether inline scripts may run. With a strict policy, an XSS injection that slips through cannot run its script, because the browser refuses it. The difficulty with WordPress is that core, the block editor, themes and plugins print a lot of inline scripts and styles, so a strict policy turned on at once breaks the site.

Problem: The site has no browser-side protection against XSS: if an injection point is found, the attacker’s JavaScript runs in visitors’ browsers.

Solution: Start with Content-Security-Policy-Report-Only, collect the violations, give WordPress’ own inline scripts a per-request nonce, tighten the policy step by step, and only then enforce it. Front end only; the admin is left alone.

The header with a nonce

In a plugin:

<?php
function myplugin_csp_nonce() {
    static $nonce = null;
    if ( null === $nonce ) {
        $nonce = base64_encode( random_bytes( 16 ) ); // new on every request
    }
    return $nonce;
}

add_action( 'send_headers', function () {
    if ( is_admin() ) {
        return;
    }

    $nonce  = myplugin_csp_nonce();
    $policy = implode( '; ', array(
        "default-src 'self'",
        "script-src 'self' 'nonce-{$nonce}' https://www.googletagmanager.com",
        "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
        "font-src 'self' https://fonts.gstatic.com",
        "img-src 'self' data: https:",
        "connect-src 'self' https://www.google-analytics.com",
        "frame-ancestors 'self'",
        "base-uri 'self'",
        "object-src 'none'",
        'report-uri ' . esc_url_raw( rest_url( 'myplugin/v1/csp-report' ) ),
    ) );

    header( 'Content-Security-Policy-Report-Only: ' . $policy );
    // After the violations are fixed:
    // header( 'Content-Security-Policy: ' . $policy );
} );

// The nonce on the script tags WordPress prints
add_filter( 'wp_script_attributes', function ( $attributes ) {
    $attributes['nonce'] = myplugin_csp_nonce();
    return $attributes;
} );
add_filter( 'wp_inline_script_attributes', function ( $attributes ) {
    $attributes['nonce'] = myplugin_csp_nonce();
    return $attributes;
} );

The two filters (WordPress 5.7+) add the nonce to the tags built by wp_get_script_tag() and wp_get_inline_script_tag(). Since WordPress 6.3 the enqueued scripts and their inline data (wp_localize_script(), wp_add_inline_script()) are printed through these functions, so they all get the nonce. Scripts that themes or plugins echo directly as raw <script> do not, and they are what the reports will show.

Styles keep 'unsafe-inline' here: WordPress prints the global styles and block supports as inline <style> without a nonce. Inline styles are a much smaller risk than inline scripts, so this is a reasonable compromise.

frame-ancestors 'self' is the modern replacement for X-Frame-Options, and object-src 'none' with base-uri 'self' closes two other classic injection paths.

Collect the reports

<?php
add_action( 'rest_api_init', function () {
    register_rest_route( 'myplugin/v1', '/csp-report', array(
        'methods'             => 'POST',
        'permission_callback' => '__return_true',
        'callback'            => function ( WP_REST_Request $request ) {
            $report = json_decode( $request->get_body(), true );
            $data   = $report['csp-report'] ?? array();
            error_log( sprintf(
                'CSP: %s blocked %s on %s',
                sanitize_text_field( $data['violated-directive'] ?? '?' ),
                esc_url_raw( $data['blocked-uri'] ?? '?' ),
                esc_url_raw( $data['document-uri'] ?? '?' )
            ) );
            return new WP_REST_Response( null, 204 );
        },
    ) );
} );

The endpoint is public by nature (browsers send the reports without authentication), so it only logs a few sanitized fields and never outputs anything. Browse the main pages for a week or two, add the legitimate sources from the log to the policy, and switch the header name to enforce mode.

Page cache

With a full page cache, the cached HTML contains the nonce of the request that created it. Nginx FastCGI cache and most caching plugins store the response headers too, so header and HTML still match, but the nonce is then the same for all visitors until the cache expires, which weakens it. For a cached site, consider generating the header at the web server or CDN level with a hash-based policy, or accept the trade-off consciously.

NOTE: The other security headers (X-Content-Type-Options, Referrer-Policy, Permissions-Policy, HSTS) are independent of CSP and simpler, see HTTP security headers via .htaccess. If you set CSP in PHP, do not set another CSP header in the web server: the browser enforces both, and the stricter one wins.