Enforcing Content Security Policy (CSP) with Nginx
Owner: SnippetBot
Created: 2026-11-03 00:00:48
Size: 1.86 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# /etc/nginx/sites-available/your_site.conf
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name yourdomain.com;
# Other SSL/TLS configurations...
# Content Security Policy (CSP)
# This example allows:
# - default-src: only from same origin
# - script-src: same origin, 'self', explicit trusted domains, 'nonce' or 'sha' for inline scripts (avoid 'unsafe-inline' in production)
# - style-src: same origin, 'self', explicit trusted domains, 'unsafe-inline' (for development/small inline styles)
# - img-src: same origin, 'self', data: images, explicit trusted domains
# - connect-src: same origin, 'self', specific APIs
# - font-src: same origin, 'self', CDN for fonts
# - object-src: none (prevents plugins)
# - base-uri: 'self' (prevents injection of base tags)
# - form-action: 'self' (restricts form submission endpoints)
# - frame-ancestors: 'self' (prevents clickjacking, supersedes X-Frame-Options)
# - upgrade-insecure-requests: rewrites HTTP requests to HTTPS
# - block-all-mixed-content: blocks HTTP assets on HTTPS page
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trustedcdn.com 'nonce-randomstring' 'unsafe-hashes' 'sha256-base64hash'; style-src 'self' https://trustedcdn.com 'unsafe-inline'; img-src 'self' data: https://trustedcdn.com; connect-src 'self' https://api.example.com; font-src 'self' https://fonts.gstatic.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; upgrade-insecure-requests; block-all-mixed-content;";
# Optional: Report-Only CSP header to test policies without blocking content
# add_header Content-Security-Policy-Report-Only "default-src 'self'; report-uri /csp-report-endpoint;";
# Other configurations for your site...
}