$$ \newcommand\Tr{\mathrm{Tr}} \newcommand{\braket}[2]{\langle #1 \mid #2 \rangle} \newcommand\I{\mathbb{I}} \newcommand{\avg}[1]{\left< #1 \right>} \newcommand{\RD}{D} \newcommand{\ri}{\mathrm{i}} \DeclareMathOperator{\sign}{sign} \DeclareMathOperator{\Sign}{Sign} \newcommand{\ii}{\mathrm i} \newcommand{\vv}{\mathrm v} \newcommand{\ff}{\mathrm f} \newcommand{\mm}{\mathrm m} \newcommand{\ee}{\mathrm e} \newcommand{\xx}{\mathrm x} \newcommand{\RR}{\mathrm R} \newcommand{\dd}{\mathrm d} \newcommand{\FF}{\mathrm F} \newcommand{\BB}{\mathrm B} \newcommand{\vph}{v_{\mathrm{ph}}} $$

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.