Essential HTTP Security Headers for Nginx
Owner: SnippetBot
Created: 2026-08-17 00:00:41
Size: 2.70 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri; # Redirect HTTP to HTTPS
}
server {
listen 443 ssl http2;
server_name example.com www.example.com;
# SSL Configuration (assuming certs are configured)
# ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
# ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# ssl_session_timeout 1d;
# ssl_session_cache shared:SSL:10m;
# ssl_session_tickets off;
# ssl_protocols TLSv1.2 TLSv1.3;
# ssl_ciphers "EECDH+AESGCM:EDH+AESGCM";
# ssl_prefer_server_ciphers on;
# 1. HTTP Strict Transport Security (HSTS) - Force HTTPS for future requests
# max-age should be at least 6 months (15768000 seconds). includeSubDomains if applicable.
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
# 2. X-Frame-Options - Prevent Clickjacking attacks
# DENY: No rendering in a frame. SAMEORIGIN: Only same origin allowed.
add_header X-Frame-Options "DENY" always;
# 3. X-Content-Type-Options - Prevent MIME-sniffing
add_header X-Content-Type-Options "nosniff" always;
# 4. Content Security Policy (CSP) - Mitigate XSS and data injection
# Customize directives (default-src, script-src, style-src, img-src, etc.)
# Example: Allow self for scripts, styles, images, and only example.com for connect-src
add_header Content-Security-Policy "default-src 'self'; \
script-src 'self' www.googletagmanager.com; \
style-src 'self' 'unsafe-inline'; \
img-src 'self' data:; \
connect-src 'self' api.example.com; \
font-src 'self'; \
object-src 'none'; \
frame-ancestors 'none'; \
base-uri 'self';" always;
# 5. Referrer-Policy - Control how much referrer information is sent
add_header Referrer-Policy "no-referrer-when-downgrade" always;
# 6. X-XSS-Protection - Enable browser's built-in XSS filter (deprecated, CSP is better)
# Kept for compatibility with older browsers.
add_header X-XSS-Protection "1; mode=block" always;
# 7. Permissions-Policy (Feature-Policy in older specs) - Control browser features
# Example: Disable camera, geolocation for embedded content
add_header Permissions-Policy "camera=(), geolocation=(), microphone=()" always;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}