Adding Content Security Policy (CSP) to Hugo Site

This tutorial will show you how to add Content Security Policty (CSP) to Hugo site.

Introduction

Content Security Policy (CSP) is designed to prevent Cross Site Scripting (XSS) Attack. For example, when we add stylesheet script from Bootstrap CDN, the script will have access to our website. With this policy, we restrict the origin that will have access to our site.

Adding CSP

There are several ways to add CSP to Hugo site. You can use either of these:

CSP Meta Tag

This method can be applied to any website, not limited to Hugo, by adding csp meta tag inside <head> like below.


<meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-eval' 'unsafe-inline' www.google-analytics.com www.googletagmanager.com fonts.googleapis.com maxcdn.bootstrapcdn.com fonts.gstatic.com;">

_headers File

This method is specific to Netlify if you deploy your site in Netlify. You have to add _headers file without extension in your publish directory, typically public folder, then add below plaintext.

/*
  Content-Security-Policy: default-src 'self' 'unsafe-eval' 'unsafe-inline' www.google-analytics.com www.googletagmanager.com fonts.googleapis.com maxcdn.bootstrapcdn.com fonts.gstatic.com;

Netlify Configuration File

This method is also specific to Netlify. You have to create netlify.toml file in your website root folder then add below code.

[[headers]]
  for = "/*"
  [headers.values]
    Content-Security-Policy = "default-src 'self' 'unsafe-eval' 'unsafe-inline' www.google-analytics.com www.googletagmanager.com fonts.googleapis.com maxcdn.bootstrapcdn.com fonts.gstatic.com;"

Hugo Configuration File

You need to modify Hugo config file config.yml, config.toml, or config.json by adding below code.

[[headers]]
  for = "/*"
  [headers.values]
    Content-Security-Policy = "default-src 'self' 'unsafe-eval' 'unsafe-inline' www.google-analytics.com www.googletagmanager.com fonts.googleapis.com maxcdn.bootstrapcdn.com fonts.gstatic.com;"

Conclusion

The first method applies generally on any website.

The second method and the third method are specific to Netlify. But, the third one is more recommended because we can add another script related to Netlify deployment.

The last method is similar with the third method where the difference is only the file where the policy is added.