Harden your Laravel app with CSP headers

Jul 8, 2021 by Thibault Debatty | 4583 views

Laravel Secure Software Development Docker Cyber-Wise


CSP (Content Security Policy) reduces the risk of cross-site scripting and other content-injection attacks by defining, at the level of the webserver, a header that whitelists authorized sources of content for your website.

There is no policy that fits all websites. Hence CSP is not enabled by default on a Laravel app. So here is an example that you should add to the file public/.htaccess:

<IfModule mod_headers.c>
  # https://cylab.be/blog/155/harden-your-laravel-app-with-csp-headers
  Header set Content-Security-Policy "default-src 'self'; style-src 'self' fonts.googleapis.com; object-src 'none'; form-action 'self'; font-src 'self' fonts.gstatic.com"

In this example:

  • by default js and css files can only be downloaded from the same domain;
  • css files can be downloaded from the domain self, or from fonts.googleapis.com;
  • <object>, <embed> and <applet> are blocked;
  • form can only be POSTed to the same domain;
  • fonts can be downloaded from the same domain, or from fonts.googleapis.com.

CSP has a lot of available directives. To help you define your CSP you can use an online CSP header generator. You can also use a validator that will explain the result of your CSP.

For this to work, you must enable the headers module on your server:

sudo a2enmod headers

Or, if you are using Docker, you must add this command to your Dockerfile:

RUN a2enmod headers


You can check the header is correctly sent by your server using the 'Network' tab of your browser.

This example is taken from our Cyber-Wise project.

This blog post is licensed under CC BY-SA 4.0

This website uses cookies. More information about the use of cookies is available in the cookies policy.