Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement Content Security Policy using local htaccess file (Apache)

I'm new to web dev and want to implement Content Security Policy on a certain web page only.

This is what I have done so far: 1. Set header this way:

Header set Content-Security-Policy "
    default-src 'self';
    script-src 'self';
" 
  1. Got a 500 internal server error after this setting. Read somewhere that mod_headers must be enabled. So enabled it using:
sudo a2enmod headers
sudo service apache2 restart
  1. .htaccess looks like this now:
<IfModule mod_headers.c>Header set Content-Security-Policy "

    default-src 'self';

    script-src 'self';

"</IfModule>

Right now, the problem is that I'm not getting any error now but the header is still not set. Please advise me if I'm missing something. I've gone through other threads already and followed this whole path using: How to implement content security policy? and some other questions too. P.S I'm using Apache and PHP on Ubuntu 14.04

like image 201
Hassan Mussana Avatar asked Sep 06 '25 20:09

Hassan Mussana


1 Answers

For anyone who wants to use line breaks (and you're going to want to use line breaks for really complex CSPs), Apache allows them by simply ending a line with a backslash ( \ ) to indicate that the command continues on the next line. For example (taken from Hassan's original post):

<IfModule mod_headers.c>Header set Content-Security-Policy "\
    \
    default-src 'self'; \
    \
    script-src 'self'; \
    \
"</IfModule>

Note that the white space before the backslash does not matter; you can have the backslash immediately after a non-whitespace character or you can add one or more spaces, tabs, etc. and then end with the slash. Blank lines must include the backslash as the last character on the line.

Reference: https://httpd.apache.org/docs/current/configuring.html

httpd configuration files contain one directive per line. The backslash "\" may be used as the last character on a line to indicate that the directive continues onto the next line. There must be no other characters or white space between the backslash and the end of the line.

like image 135
John T. Avatar answered Sep 09 '25 12:09

John T.