# /etc/nginx/snippets/security-headers.conf
# Prevent clickjacking
add_header X-Frame-Options "SAMEORIGIN" always;
# Prevent MIME type sniffing
add_header X-Content-Type-Options "nosniff" always;
# XSS protection
add_header X-XSS-Protection "1; mode=block" always;
# Referrer policy
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# HSTS (HTTPS only - be careful with this)
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
# Permissions policy (formerly Feature-Policy)
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
Content Security Policy
# Basic CSP
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';" always;
# CSP with external resources
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' https://fonts.googleapis.com; img-src 'self' https: data:; font-src 'self' https://fonts.gstatic.com;" always;
# Report-only mode (for testing)
add_header Content-Security-Policy-Report-Only "default-src 'self'; report-uri /csp-report" always;
Complete Security Configuration
server {
listen 443 ssl http2;
server_name example.com;
# SSL configuration
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# Security headers
include snippets/security-headers.conf;
# Hide nginx version
server_tokens off;
# Limit request body size
client_max_body_size 10M;
# Prevent access to hidden files
location ~ /\. {
deny all;
}
# Prevent access to sensitive files
location ~* \.(env|log|htaccess|htpasswd|ini|conf)$ {
deny all;
}
root /var/www/example.com;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
# Check headers
curl -I https://example.com
# Online tools:
# - https://securityheaders.com
# - https://observatory.mozilla.org
| Header |
Purpose |
| X-Frame-Options |
Prevents clickjacking |
| X-Content-Type-Options |
Prevents MIME sniffing |
| X-XSS-Protection |
Legacy XSS filter (browsers) |
| Strict-Transport-Security |
Forces HTTPS |
| Content-Security-Policy |
Controls resource loading |
| Referrer-Policy |
Controls referer header |
| Permissions-Policy |
Controls browser features |
intermediate | Security | Updated 2025-01-15
- nginx
- security
- headers
- csp
- hsts
- xss