Setting Content Security Policy and other security related headers
-
I just spend ages figuring out how to set Content Security Policy Headers using .htaccess (although it can be done directly in php / html also if desired) and I thought I would share the results for anyone else trying to do the same.
Obviously you’ll have to modify this to match your own particular situation. The
Content-Security-Policy-Report-Only
header field is useful for testing which I would recommend.The main reference for CSP is https://www.w3.org/TR/CSP/
Specific Browser support can be seen here https://caniuse.com/#feat=contentsecuritypolicyHere is my final htaccess code section…
<ifModule mod_headers.c> # Security improvements Header unset Server #Header unset X-Pingback Header unset Accept-Ranges # <FilesMatch "\.html> Header set X-Frame-Options "SAMEORIGIN" # BrowserMatch MSIE ie Header set Imagetoolbar "no" env=ie Header set X-Content-Type-Options "nosniff" env=ie Header set X-UA-Compatible "IE=edge" env=ie Header set X-XSS-Protection "1;mode=block" env=ie Header set X-Content-Security-Policy "default-src 'self'; img-src 'self' analytics.example.com; \ script-src 'self' analytics.example.com ajax.googleapis.com; font-src 'self' data:" env=ie # BrowserMatch Firefox ff Header set Content-Security-Policy "default-src 'self'; img-src 'self' analytics.example.com; \ script-src 'self' analytics.example.com ajax.googleapis.com; \ font-src 'self' data:" env=ff # BrowserMatch SAFARI safari Header set X-XSS-Protection "1;mode=block" env=safari Header set X-WebKit-CSP "default-src 'self'; img-src 'self' analytics.example.com; \ script-src 'self' analytics.example.com ajax.googleapis.com; font-src 'self' data:" env=safari # BrowserMatch CHROME ch Header set X-Content-Type-Options "nosniff" env=ch Header set X-WebKit-CSP "default-src 'none'; img-src 'self' analytics.example.com; \ script-src 'self' analytics.example.com ajax.googleapis.com; font-src 'self' data:" env=ch # BrowserMatch chromeframe chf Header set Imagetoolbar "no" env=chf Header set X-Content-Type-Options "nosniff" env=chf Header set X-UA-Compatible "IE=edge,chrome=1" env=chf Header set X-XSS-Protection "1;mode=block" env=chf Header set X-WebKit-CSP "default-src 'none'; img-src 'self' analytics.example.com; \ script-src 'self' analytics.example.com ajax.googleapis.com; font-src 'self' data:" env=chf </FilesMatch> </IfModule>
I’d be very interested to hear of any suggested improvements or changes.
During my testing with FF Firebug I had a couple of CSP warnings that don’t appear in the native dev tool console in Firefox (e.g. it complained about the googleapis domain until both the http and https versions were specifically included. In the end concluded these were due to issues with or using Firebug in this context rather than a problem with the headers themselves.
- The topic ‘Setting Content Security Policy and other security related headers’ is closed to new replies.