Guide to Setting the "Content-Security-Policy" Header

Contents

What Does This Header Do?

The Content-Security-Policy (CSP) header helps protect your website from attacks like cross-site scripting (XSS) by specifying which sources of content are allowed to be loaded on your site. It provides fine-grained control over resources such as scripts, styles, images, and more.

Steps to Set the Header

1. If You Use a Web Server (e.g., Apache, Nginx, etc.)

For Apache:

  1. Open your website's configuration file (or .htaccess file if you use one).
  2. Add the following line, replacing the policy with one tailored to your needs:
    Header set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self';"
  3. Save the file and restart the Apache server to apply changes.

For Nginx:

  1. Open your website's configuration file (e.g., /etc/nginx/sites-available/your-site).
  2. Add the following line inside the server block, replacing the policy with one tailored to your needs:
    add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self';";
  3. Save the file and restart Nginx to apply changes using:
    sudo systemctl restart nginx

2. If You Use a Programming Language:

For PHP:

header("Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self';");

For Node.js:

Use a middleware like helmet to set the header automatically:

const helmet = require('helmet');
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'"],
    styleSrc: ["'self'"]
  }
}));

Or set it manually:

app.use((req, res, next) => {
  res.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self';");
  next();
});

For Python (Flask):

from flask import Flask, Response

app = Flask(__name__)

@app.after_request
def set_headers(response):
    response.headers['Content-Security-Policy'] = "default-src 'self'; script-src 'self'; style-src 'self';"
    return response

3. Verify the Header

After setting the header, test your website to ensure itโ€™s working:

  1. Open your website in a browser.
  2. Use the developer tools (right-click > Inspect > Network tab) to view the HTTP headers.
  3. Look for the Content-Security-Policy header with the correct value.

Why It Matters

Setting this header helps prevent malicious scripts or resources from being loaded on your website, significantly reducing the risk of attacks like XSS and ensuring a safer browsing experience for your users.