The short answer
Security headers are HTTP response directives that tell browsers how to handle content. Adding them in nginx is done by editing the server block and reloading the service, which instantly improves protection against clickjacking, XSS and other attacks.
What security headers are and why they matter
Security headers are HTTP response directives that tell browsers how to handle content from your site. They are added by the web server and processed by the client, influencing caching, framing, script execution, and transport security. By defining these policies centrally, you reduce reliance on application‑level code and provide a consistent defense against common web attacks such as click‑jacking, cross‑site scripting, and man‑in‑the‑middle interception.
The most widely used headers include Content‑Security‑Policy, which restricts the sources from which scripts, styles, and media can be loaded; X‑Content‑Type‑Options: nosniff, which forces browsers to honor declared MIME types; X‑Frame‑Options or Content‑Security‑Policy: frame‑ancestors, which prevent unauthorized framing; Referrer‑Policy, which controls how much referrer information is sent; and Strict‑Transport‑Security, which forces HTTPS connections. Together they create multiple layers of protection that complement firewalls and application hardening.
- Content‑Security‑Policy – limits allowed origins for scripts, styles, images, etc.
- X‑Content‑Type‑Options: nosniff – stops MIME‑type sniffing.
- X‑Frame‑Options or CSP frame‑ancestors – blocks click‑jacking.
- Referrer‑Policy – reduces leakage of URL information.
- Strict‑Transport‑Security – enforces HTTPS.
# Example: add common security headers in an nginx server block
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trusted.cdn.com";
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "SAMEORIGIN";
add_header Referrer-Policy "no-referrer-when-downgrade";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";After reloading nginx, check the response headers with a tool like curl -I https://yourdomain.com. Verify that each header appears with the expected values and that no syntax errors were reported during the reload.
How to verify current headers on your site
Before adding or modifying security headers, confirm what your server is already sending. The easiest way is to request the page and view the HTTP response headers. You can use a web browser’s developer tools – open the Network tab, reload the page, and click the request to see the “Headers” section. This shows all response headers, including any security‑related ones like Content‑Security‑Policy, X‑Frame‑Options, or Referrer-Policy. Browsers display them in a readable format and require no additional software.
Command‑line tools are useful for quick checks or automated scripts. curl and wget can fetch a URL and print only the response headers. These utilities work on any Linux server with network access and do not modify the remote site. Use them to compare the output before and after you change your Nginx configuration, ensuring the intended headers appear and no unexpected ones are missing. Remember to run the commands as a regular user and review the output before making changes.
- Use browser developer tools (Network tab) to view headers.
- Run
curl -I https://example.comto list response headers. - Run
wget --server-response --spider https://example.comfor a similar view. - Check for headers like
Content-Security-Policy,X-Frame-Options,Strict-Transport-Security.
curl -I https://yourdomain.com
wget --server-response --spider https://yourdomain.comLook for the presence of the security headers you plan to set. If a header is missing, you will need to add it in the Nginx configuration and reload the service. Verify that values match your policy, such as Content-Security-Policy: default-src 'self' or X-Frame-Options: SAMEORIGIN. Consistent output across tools confirms the headers are correctly applied.
Preparing your nginx configuration for changes
Before you edit any nginx configuration, create a copy of the current files. Use a version‑controlled directory or a simple archive so you can revert if something goes wrong. A typical approach is to copy the entire /etc/nginx tree to a timestamped location, then verify the copy exists. This gives you a safety net and a reference point for later comparison, which is especially useful on production VPS or dedicated servers where downtime must be minimized.
Next, identify the server block that serves the site you want to protect. On most installations the files reside in /etc/nginx/conf.d/ or /etc/nginx/sites‑available/. Look for a server { … } stanza that contains the server_name matching your domain. If the configuration uses include directives, follow them until you find the exact file that defines the virtual host. Knowing the correct file prevents accidental changes to unrelated sites.
- Create a backup with
tar -czf /root/nginx-backup-$(date +%F).tgz /etc/nginx - Locate the active server block in
/etc/nginx/sites-available/or/etc/nginx/conf.d/ - Test the configuration after changes with
nginx -t
# Example commands – read them before running
# 1. Backup nginx configuration
tar -czf /root/nginx-backup-$(date +%F).tgz /etc/nginx
# 2. Find the file that contains your domain
grep -rl "server_name yourdomain.com" /etc/nginx/sites-available /etc/nginx/conf.d
# 3. Verify syntax after editing
nginx -tAfter running nginx -t you should see a message stating the configuration file syntax is ok and the test is successful. If any errors appear, revisit the edited file, correct the issue, and retest before reloading nginx.
Step‑by‑step: adding recommended headers
To add the recommended security headers in nginx, edit the server block or a dedicated include file. Insert the following directives inside the location / or server context: add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trusted.cdn.com; object-src 'none';" always;, add_header X-Content-Type-Options "nosniff" always;, add_header X-Frame-Options "SAMEORIGIN" always;, add_header Referrer-Policy "strict-origin-when-cross-origin" always;, and add_header Permissions-Policy "geolocation=(), microphone=()" always;. These headers tell browsers how to handle content, block MIME sniffing, prevent click‑jacking, control referrer information, and restrict use of powerful browser features.
After adding the directives, test the configuration with nginx -t and reload nginx using a safe command such as systemctl reload nginx. When the server restarts, browsers will receive the new headers in every response. Verify their presence with browser developer tools or an online header checker to ensure they are correctly applied.
Look for the headers in the response section of your browser’s network inspector. Each header should appear exactly as defined, and there should be no syntax errors reported by nginx during the reload.
Testing the new configuration safely
After editing the nginx configuration, always test the file for syntax errors before applying it. Use the built‑in validator with nginx -t; it will report any problems without affecting the running service. If the test passes, you can reload the worker processes safely using systemctl reload nginx (or service nginx reload on older systems). Reloading reads the new configuration while keeping existing connections open, so there is no downtime for visitors.
Once nginx has reloaded, verify that the security headers are being sent. The simplest method is to issue a request with curl -I https://yourdomain.com and look for the expected header lines in the output. You can also pipe the result to grep to filter only the security headers, which makes the check quicker. Perform the test from a machine that can reach the server directly to avoid proxy interference.
- Run
nginx -tto validate the configuration syntax. - Use
systemctl reload nginxto apply changes without stopping the service. - Execute
curl -I https://yourdomain.comto view response headers. - Optionally pipe to
grep -i "content-security-policy"to focus on specific headers.
nginx -t
systemctl reload nginx
curl -I https://yourdomain.com | grep -i "strict-transport-security"The curl output should list each of the security headers you added, such as Content‑Security‑Policy, X‑Content‑Type‑Options, and Strict-Transport-Security. If any header is missing, revisit the nginx block where you defined them and repeat the test.
What to avoid when configuring headers
When adding security headers in nginx, avoid making the Content‑Security‑Policy (CSP) too restrictive. A CSP that blocks all inline scripts, styles, or required third‑party domains can break site functionality and lead to a poor user experience. Test the policy in report‑only mode first, then gradually tighten it. Also, do not duplicate header directives in multiple locations; having the same header set in both the http block and a server block can cause unexpected overrides and make troubleshooting harder.
Another common mistake is setting overly permissive values, such as using * in the frame‑ancestors directive or allowing unsafe-inline in CSP without a clear need. These weaken the protection you intend to provide. Likewise, forgetting to include the X‑Content‑Type‑Options: nosniff header leaves browsers able to sniff MIME types, which can be exploited. Keep the header list concise and purpose‑driven, and review each directive for relevance to your application.
- Do not use
*in CSP source lists unless absolutely necessary. - Avoid setting the same header in both http and server blocks.
- Never enable
unsafe-inlineorunsafe-evalwithout justification. - Do not omit
X‑Content‑Type‑Options: nosniff. - Avoid using
frame‑ancestors *which defeats click‑jacking protection.
curl -I https://yourdomain.com | grep -i "content-security-policy"After applying the headers, request a page and inspect the response headers. Verify that each header appears once with the expected value and that the CSP does not generate violations in the browser console.
Maintaining header security over time
Regularly reviewing the response headers you serve is essential because configuration drift can introduce gaps over time. Schedule a quarterly audit that checks each virtual host for the required security directives such as Content‑Security‑Policy, X‑Content‑Type‑Options, Referrer-Policy, and Strict‑Transport‑Security. Use a checklist or a simple script that extracts the header block from the live server and compares it with the approved baseline. This practice catches accidental removals, syntax errors, or new directives that may conflict with existing policies.
Store your nginx configuration files in a version‑control system like Git. Commit every change, tag releases, and require peer review before merging. With version control you can track who altered a header, when, and why, and you can roll back if a change breaks the site. Complement this with a monitoring tool that watches the configuration directory for modifications and alerts the admin team. Automated alerts give you early warning of unexpected edits, whether from a human operator or a compromised account.
- Run a quarterly script to dump current headers and compare with the baseline.
- Commit all nginx config files to Git and use pull‑request reviews.
- Enable file‑system monitoring (e.g.,
inotifywait) on/etc/nginx/for changes. - Document header decisions in a central policy file.
- Test header changes in a staging environment before production deployment.
## Example: list current header directives and diff with Git baseline
# Show the header block from the active config (example for site example.com)
nginx -T | grep -A5 'add_header' | grep 'example.com' > /tmp/current-headers.txt
# Compare with the version‑controlled baseline
git show HEAD:sites-available/example.com.conf | grep 'add_header' > /tmp/baseline-headers.txt
diff -u /tmp/baseline-headers.txt /tmp/current-headers.txt || echo "No differences"The diff output should be empty or only show expected updates. Any unexpected additions or missing directives indicate a configuration drift that needs correction.
If you would rather have engineers do this for you, see Linux server management, Windows server management or emergency malware cleanup.
Questions people ask
Which security headers give the biggest protection for a typical website?
The most impactful headers are X‑Content‑Type‑Options, X‑Frame‑Options, Referrer‑Policy, and Content‑Security‑Policy. They stop MIME sniffing, click‑jacking, referrer leaks, and script injection. Adding them together gives a strong baseline protection for most sites.
How can I test that my CSP header does not break legitimate content?
To test a CSP header, enable it in report‑only mode first. Use the browser console or the `Content-Security-Policy-Report-Only` header to see violations. Check that all images, scripts, and styles load and that no errors appear before enforcing it.
Do I need to restart nginx after adding headers, or is reload enough?
A reload (`nginx -s reload`) is enough after adding or changing headers. Restarting is not required unless you modify the main configuration file structure. Reload reloads the config without dropping connections.
What should I do if a third‑party script conflicts with my security headers?
If a third‑party script needs a policy that conflicts with your CSP, either allow that specific source in the CSP or host the script locally and serve it from a trusted domain. If that isn’t possible, consider using a separate sub‑domain with a relaxed CSP and embed it via an iframe.