How to Set Security Headers in Nginx for Better Protection
To set security headers in
nginx, add add_header directives inside your server or location block in the configuration file. Common headers include Content-Security-Policy, X-Frame-Options, and Strict-Transport-Security to protect your site from attacks.Syntax
The add_header directive in Nginx sets HTTP headers sent to clients. It has this syntax:
add_header <header-name> <header-value> [always];
The always flag ensures the header is added even on error responses.
nginx
add_header X-Frame-Options "DENY" always;Example
This example shows how to set common security headers in the server block of your Nginx config to improve security.
nginx
server {
listen 80;
server_name example.com;
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trusted.cdn.com;" always;
location / {
root /var/www/html;
index index.html;
}
}Common Pitfalls
Common mistakes when setting security headers in Nginx include:
- Not using the
alwaysflag, so headers are missing on error pages. - Placing
add_headerinsidelocationblocks without repeating in all locations, causing inconsistent headers. - Incorrect syntax like missing quotes or semicolons.
- Setting conflicting headers that break site functionality.
nginx
## Wrong: Missing 'always' flag, header not sent on errors add_header X-Frame-Options "DENY"; ## Right: Use 'always' to ensure header is sent on all responses add_header X-Frame-Options "DENY" always;
Quick Reference
| Header | Purpose | Example Value |
|---|---|---|
| X-Frame-Options | Prevents clickjacking by controlling iframe embedding | "DENY" |
| X-Content-Type-Options | Stops browsers from MIME-sniffing a response | "nosniff" |
| Strict-Transport-Security | Enforces HTTPS connections | "max-age=31536000; includeSubDomains" |
| Content-Security-Policy | Controls resources the browser can load | "default-src 'self'; script-src 'self' https://trusted.cdn.com;" |
| Referrer-Policy | Controls referrer information sent with requests | "no-referrer" |
Key Takeaways
Use the add_header directive in nginx to set security headers inside server or location blocks.
Always include the 'always' flag to ensure headers are sent on all responses, including errors.
Set common headers like X-Frame-Options, X-Content-Type-Options, and Strict-Transport-Security for better security.
Avoid placing add_header only in some locations to prevent inconsistent header delivery.
Check syntax carefully to avoid configuration errors that prevent nginx from starting.