Custom WordPress Security Headers with Dynamic CSP Nonce Generation

A healthcare research organization needed enterprise-grade security headers to protect sensitive medical research data and comply with strict data protection regulations. The standard WordPress security plugins lacked the flexibility to implement modern Content Security Policy with nonce-based script validation while maintaining compatibility with essential third-party services.

Solution

A custom security headers plugin with dynamic nonce generation and comprehensive Content Security Policy implementation. The solution automatically injects cryptographic nonces into script, style, and iframe tags during final output buffering. This approach provides strict CSP protection without requiring manual code modifications across existing templates and plugins.

Technical Implementation

  • Output buffering system captures all HTML before it reaches the browser for nonce injection.
  • Random nonce generation creates unique Base64-encoded cryptographic tokens for each page load.
  • Automatic tag modification adds nonce attributes to all script, style, object, and iframe elements via a regular expression pattern.
  • Comprehensive CSP headers include strict-dynamic directives that allow only nonce-validated resources to execute.
  • Third-party service whitelisting maintains compatibility with Google Analytics, HubSpot forms, and hCaptcha while blocking unauthorized scripts.
  • Additional security headers, including X-XSS-Protection, X-Frame-Options, and Strict-Transport-Security for defense in depth.
  • Backward compatibility mode uses unsafe-inline as a fallback for older browsers that don’t support CSP nonces.

Results

The organization achieved A+ security ratings on SecurityHeaders.com without any theme or plugin modifications. The nonce-based CSP system successfully blocks all unauthorized script execution while maintaining full functionality of analytics, forms, and CAPTCHA systems. The zero-configuration approach eliminated the need for ongoing maintenance of security headers as new scripts are added to the site.