Content Security Policy (CSP) headers are a vital security feature for static websites. They help prevent cross-site scripting (XSS) attacks by controlling which resources can be loaded and executed. Implementing CSP headers correctly can significantly enhance your website's security posture.

What is a Content Security Policy (CSP)?

A Content Security Policy is a set of rules defined by your website that instruct browsers on how to handle resources like scripts, styles, images, and other content. By specifying trusted sources, CSP helps block malicious content that could compromise your site or its visitors.

Why Use CSP Headers in Static Websites?

Static websites often serve content directly from files without server-side processing. Adding CSP headers provides an extra layer of security, reducing the risk of malicious scripts or data injection. This is especially important as static sites become more complex and integrate third-party resources.

How to Implement CSP Headers

Implementing CSP headers involves configuring your web server to send the appropriate headers with each response. The method depends on your server type.

Using Apache

Add the following line to your .htaccess file or your server configuration:

Header set Content-Security-Policy "default-src 'self'; script-src 'self' https://trustedscript.com; style-src 'self' https://trustedstyles.com;"

Using Nginx

Include the following in your server block configuration:

add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trustedscript.com; style-src 'self' https://trustedstyles.com;"

Best Practices for CSP

  • Start with a report-only policy to test your rules without blocking content.
  • Use specific sources rather than broad directives like 'unsafe-inline' or 'unsafe-eval'.
  • Regularly review your CSP to adapt to new resources or changes.
  • Combine CSP with other security measures such as HTTPS and secure cookies.

Testing Your CSP

Use browser developer tools or online CSP testing tools to verify your policies. Check the console for violations and adjust your rules accordingly. Remember to switch from report-only mode to enforced mode once you're confident your CSP is correctly configured.

Conclusion

Implementing CSP headers in static websites is a straightforward but powerful way to enhance security. By carefully defining your policies and testing them thoroughly, you can protect your site and visitors from many common web vulnerabilities.