CSP Header Format and Syntax
You'll learn how Content-Security-Policy headers are structured and how to properly format multiple directives.
The Basic Structure
A Content-Security-Policy header is essentially a single HTTP header containing one or more directives separated by semicolons. Each directive consists of a directive name followed by one or more values (called "sources") separated by spaces.
The general pattern looks like this:
Content-Security-Policy: directive1 value1 value2; directive2 value3; directive3 value4 value5
Real-World Example
Here's what an actual CSP header might look like:
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; style-src 'self' 'unsafe-inline'; img-src *
Let's break this down:
default-src 'self'— Sets the default policy to only allow same-origin resourcesscript-src 'self' https://trusted-cdn.com— Scripts can load from same-origin OR the trusted CDNstyle-src 'self' 'unsafe-inline'— Styles from same-origin plus inline stylesimg-src *— Images from any source
Syntax Rules to Remember
- Semicolons separate directives
- Spaces separate values within a single directive
- Quotes are required around keywords like
'self','unsafe-inline','nonce-xyz', and hashes - No quotes around URLs or wildcards
- Directive names are case-insensitive, but convention uses lowercase
Key Takeaway: CSP headers use semicolons to separate directives and spaces to separate values, with strict quoting rules for keywords—master this syntax to avoid parsing errors that silently break your security policy.