Essential Security Headers for Nginx
Essential Security Headers for Nginx
Nginx implements security headers through the add_header directive. Configure them in your server block:
# Strict Transport Security
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
# X-Frame-Options
add_header X-Frame-Options "SAMEORIGIN" always;
# X-Content-Type-Options
add_header X-Content-Type-Options "nosniff" always;
# X-XSS-Protection
add_header X-XSS-Protection "1; mode=block" always;
# Referrer Policy
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Content Security Policy
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.example.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; connect-src 'self' https://api.example.com; frame-ancestors 'self'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests;" always;
# Permissions Policy
add_header Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), accelerometer=(), gyroscope=()" always;
# X-Permitted-Cross-Domain-Policies
add_header X-Permitted-Cross-Domain-Policies "none" always;
# Clear site data on logout
location /logout {
add_header Clear-Site-Data '"cache", "cookies", "storage"' always;
# Other logout logic
}
# Security headers for specific file types
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
add_header Cache-Control "public, max-age=31536000, immutable";
add_header X-Content-Type-Options "nosniff" always;
}
# Prevent access to hidden files
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}