Header unset Content-Security-Policy Header add Content-Security-Policy "default-src 'self'" Header unset X-Content-Security-Policy Header add X-Content-Security-Policy "default-src 'self'" Header unset X-WebKit-CSP Header add X-WebKit-CSP "default-src 'self'"
You may also be interested in adding those headers:
Header set X-Content-Type-Options "nosniff" Header set X-XSS-Protection "1; mode=block" Header set X-Frame-Options "DENY" Header set Strict-Transport-Security "max-age=631138519; includeSubDomains"
Content Security Policy
To help prevent against cross-site scripting attacks, the idea of the Content Security Policy was devised. While the first version of CSP was only published in 2012, it has a history running back to 2004 with attempts to resolve this issue. CSP version 2 is the current version of the standard and is supported by both Chrome and Firefox, while Safari and edge only support version 1. It works when the web server sends a special header to the web browser identifying that the server implements a content security policy. Ait then dictates from where the browser should load things like stylesheets, script files, images and fonts. The web browser should then reference this information when loading the HTML code for the site and then fail to load any files that aren’t allowed by the policy.
While this won’t render all XSS style attacks impossible, it will (when implemented well) prevent all XSS attacks involving tricking the browser to load malicious files from external websites. Implementing CSP is as simple as placing a few files of configuration in your web server configuration. When running Apache you can place this code in the virtualhost configuration for your website or in a .htaccess file for the directory your website resides within. For anyone running a website on a dedicated server or VPS then the virtualhost configuration method is recommended whilst the .htaccess file method should only be needed if your website is on shared web hosting.
How To Implement CSP
At this point I’m going to be assuming you know how to edit your virtualhost configuration or create a .htaccess file for this purpose. If not then we’ve previously provided guides explaining both that you could use for reference. So prepare your file and add the following directive:
Header set Content-Secure-Policy "default-src 'self';"
By including default-src ‘none’ in the directives the browser would block all external files that aren’t explicitly defined later in the Content-Secure-Policy header. The img-src directive uses an asterisk (*) as its source definition to illustrate that it should allow images to be allowed from any domain. Hopefully, the rest of it should be fairly straight forward.
Once you’ve created your Content-Secure-Policy header you can save your file, and if you’ve included the directive within your virtualhost declaration rather than in a .htaccess file, don’t forget to reload the Apache configuration for your changes to take effect.