CSP
header with htaccess
Content-Security-Policy
HTTP response header using an Apache .htaccess
file.Let's suppose we want to add a CSP policy to our site using the following:
Header add Content-Security-Policy "default-src 'self';"
Your policy will go inside the double quotes in the example above. If everything is working you should see the following in the HTTP response headers when you make a request to your site:
Content-Security-Policy: default-src 'self';
As we saw, it is not hard to add a CSP header with htaccess, it is however also possible to add a Content-Security-Policy
header with your server side programming language (PHP, Java, etc.). You may have pages in your app that need a different CSP policy than other parts of your app. In such a case might be easier to use your application programming language instead of htaccess. In addition, if you plan to use a CSP nonce, then it is much easier to generate it, and set the Content-Security-Policy
header from your application code instead of from htaccess.
When you set the header from htaccess, the big advantage is that it will can be added to all HTTP responses (even your static assets). It may also be easier to use htaccess to add the CSP header if you have the same policy for the entire site.
There are tradeoffs however you decide to add the header. As long as the Content-Security-Policy
response header shows up in the HTTP response the browser will apply it, it doesn't care if you use htaccess or your application code.
If you're not sure what default-src 'self';
means, then check out the Content Security Policy reference for details, or take a look at more CSP examples.
Want to learn the ins and outs CSP? Grab a copy of the CSP Developer Field Guide. It's a short and sweet guide to help developers get up to speed quickly.
Grab a CopyAdvisory Week is a weekly roundup of all the security advisories published by the major software vendors.