Content Security Policy (CSP) headers are an essential security feature for WordPress websites. They help prevent cross-site scripting (XSS) attacks by controlling which resources can be loaded by the browser. Properly setting up CSP headers can significantly enhance your website's security posture.

Understanding CSP Headers

CSP headers are HTTP response headers that specify approved sources of content. When configured correctly, they restrict the types of content that can be loaded, such as scripts, images, stylesheets, and more. This limits the attack surface and helps protect your site and visitors.

Best Practices for Setting Up CSP in WordPress

1. Start with a Report-Only Policy

Before enforcing strict CSP rules, it's advisable to implement a report-only policy. This allows you to monitor violations without blocking resources, helping you fine-tune your policy without disrupting site functionality.

2. Define a Whitelist of Trusted Sources

Create a list of trusted domains for scripts, styles, images, and other resources. Use directives like script-src, style-src, and img-src to specify these sources. For example:

  • Self ('self')
  • Your CDN or hosting provider
  • Trusted third-party services (e.g., Google Fonts)

Implementing CSP Headers in WordPress

You can set CSP headers through your server configuration or via WordPress plugins. For server-level configuration, modify your .htaccess file (Apache) or server config (Nginx). For plugin-based setup, plugins like "HTTP Headers" or "Security Headers" can simplify the process.

Using .htaccess (Apache)

Add the following line to your .htaccess file:

Header set Content-Security-Policy "default-src 'self'; script-src 'self' https://trustedcdn.com; style-src 'self' https://fonts.googleapis.com;"

Using Nginx

Include the following in your server block:

add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trustedcdn.com; style-src 'self' https://fonts.googleapis.com;"

Testing and Monitoring

After implementing CSP headers, test your website thoroughly. Use browser developer tools and online CSP evaluators to identify violations. Monitor reports regularly and adjust your policy accordingly to balance security and functionality.

Conclusion

Setting up CSP headers in WordPress is a vital step toward securing your website. By starting with a report-only mode, defining trusted sources, and carefully monitoring violations, you can create an effective security policy that protects both your site and its visitors.