Skip to main content

Security and hardening · Intermediate · 14 min

How to Add Security Headers to Your Site in Nginx

By Padding · Updated 15 Nov 2026
Ubuntu 26.04.1 LTS · Nginx 1.30

You will add the HTTP security headers every site should send, keep them in one reusable file, avoid the add_header inheritance trap, and roll out Content-Security-Policy and HSTS in the safe order.

On this page

A browser trusts a page to behave unless the server says otherwise. Security headers are the way a server says otherwise. They tell the browser not to guess file types, not to let other sites frame your pages, not to leak the full URL to third parties, and to use HTTPS only. Each is one line in your Nginx configuration, and together they close several common attack routes.

In this tutorial you will put the headers in one file you can include in every site, see them in a real response, learn why a single add_header in the wrong place deletes the others, and roll out the two risky ones, Content-Security-Policy and HSTS, in a safe order. It assumes Nginx 1.30 is installed as in /tutorials/install-nginx-on-ubuntu-26-04.

Step 1 · See what your server sends today

Ask for the headers of the default page:

Bash
curl -sI http://localhost/

You see lines such as HTTP/1.1 200 OK, Server: nginx/1.30.x, Content-Type: text/html, and Content-Length. There are no security headers yet. The Server header tells every scanner exactly which version you run, which helps an attacker pick an exploit. Turn it off first. Add a file that Nginx reads for the whole http context:

Bash
sudo tee /etc/nginx/conf.d/00-security.conf > /dev/null <<'CONF'
# Do not announce the Nginx version in the Server header or on error pages.
server_tokens off;
CONF

The package already reads every *.conf file in /etc/nginx/conf.d/, so nothing else needs editing.

Step 2 · Put the headers in one snippet

Write the headers once in a file, and include that file from every server block. When you change a header, you change one place.

Bash
sudo mkdir -p /etc/nginx/snippets
sudo tee /etc/nginx/snippets/security-headers.conf > /dev/null <<'CONF'
# Do not let the browser guess a file's type from its content.
add_header X-Content-Type-Options "nosniff" always;

# Do not let other sites put this site in a frame (clickjacking).
add_header X-Frame-Options "SAMEORIGIN" always;

# Send the full URL to this site, but only the origin to other sites, and nothing over plain HTTP.
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

# Switch off browser features the site does not use.
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;

# Keep this site's windows isolated from pop-ups opened by other sites.
add_header Cross-Origin-Opener-Policy "same-origin" always;
CONF

What each one does:

  • X-Content-Type-Options: nosniff stops a browser from treating an uploaded text file as a script because it looks like one.
  • X-Frame-Options: SAMEORIGIN allows framing only from your own site. Use DENY if nothing should ever frame it. The modern replacement is the frame-ancestors part of Content-Security-Policy, covered below. Sending both is normal.
  • Referrer-Policy limits what URL information leaves your site when a visitor clicks a link.
  • Permissions-Policy turns off camera, microphone and location for your pages and any embedded frames. Add the features your site needs, for example camera=(self).
  • Cross-Origin-Opener-Policy: same-origin stops a window opened from another site from holding a reference to yours. It can break sign-in pop-ups that rely on window.opener, so test those flows.
  • The word always makes Nginx send the header on error responses (404, 500) as well as on successful ones. Without it, the header is missing exactly where you might need it.

Now include the snippet in a server block. This command edits the default site that the package installs. For your own site, add the same include line inside its server { } block:

Bash
sudo sed -i '/server_name  localhost;/a\    include /etc/nginx/snippets/security-headers.conf;' /etc/nginx/conf.d/default.conf
grep -n 'include' /etc/nginx/conf.d/default.conf

The output shows the include /etc/nginx/snippets/security-headers.conf; line just below server_name.

Test the configuration, then reload it. A reload applies the change without dropping connections:

Bash
sudo nginx -t
Bash
sudo systemctl reload nginx

Check it worked

Bash
curl -sI http://localhost/

The response now includes X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN, Referrer-Policy: strict-origin-when-cross-origin, Permissions-Policy: camera=(), microphone=(), geolocation=() and Cross-Origin-Opener-Policy: same-origin. The Server header says nginx with no version number.

Troubleshooting

  • The headers do not appear: you reloaded before nginx -t passed, or the include is outside the server block. Run sudo nginx -T | grep -n security-headers to see where Nginx loaded it.
  • nginx: [emerg] open() "/etc/nginx/snippets/security-headers.conf" failed: the path in include has a typo, or the file was not created.
  • A header appears twice: something else, such as your application, already sends it. Remove one source. Browsers handle duplicates inconsistently.

Step 3 · Avoid the add_header inheritance trap

This is the mistake that silently removes your headers. Nginx passes add_header lines down from a server block to its location blocks only if the location has no add_header of its own. The moment a location adds any header, it drops all the ones inherited from above.

See it happen. This demonstration server listens on 127.0.0.1:8081, so it is reachable from the server itself only, and its location sets a cache header:

Bash
sudo mkdir -p /usr/share/nginx/html/assets
echo 'body { margin: 0 }' | sudo tee /usr/share/nginx/html/assets/app.css > /dev/null
sudo tee /etc/nginx/conf.d/trap-demo.conf > /dev/null <<'CONF'
server {
    listen 127.0.0.1:8081;
    include /etc/nginx/snippets/security-headers.conf;

    location /assets/ {
        root /usr/share/nginx/html;
        add_header Cache-Control "public, max-age=3600" always;
    }
}
CONF
sudo nginx -t
Bash
curl -sI http://127.0.0.1:8081/assets/app.css

The response has Cache-Control: public, max-age=3600, and none of the security headers. The location replaced them.

Nginx 1.29.3 and later, including the 1.30 you installed, has a directive that fixes this cleanly. add_header_inherit merge; tells Nginx to keep the inherited headers and add the location's own on top. Put it in the server block, where it applies to every location inside:

Bash
sudo tee /etc/nginx/conf.d/trap-demo.conf > /dev/null <<'CONF'
server {
    listen 127.0.0.1:8081;
    add_header_inherit merge;
    include /etc/nginx/snippets/security-headers.conf;

    location /assets/ {
        root /usr/share/nginx/html;
        add_header Cache-Control "public, max-age=3600" always;
    }
}
CONF
sudo nginx -t
Bash
curl -sI http://127.0.0.1:8081/assets/app.css

Now the cache header and all five security headers appear together. On an older Nginx, which does not know add_header_inherit, nginx -t fails with unknown directive. There the fix is to repeat the include inside every location that adds a header:

Nginx
location /assets/ {
    root /usr/share/nginx/html;
    include /etc/nginx/snippets/security-headers.conf;
    add_header Cache-Control "public, max-age=3600" always;
}

Remove the demo when you are done, so no stray port stays open:

Bash
sudo rm /etc/nginx/conf.d/trap-demo.conf
sudo nginx -t

The same rule applies to proxy_pass locations that add headers. Check each important path with curl -I, not just the home page.

Step 4 · Add Content-Security-Policy in report-only mode

Content-Security-Policy (CSP) tells the browser which sources of scripts, styles, images and frames are allowed. It is the strongest defence against injected scripts, and the easiest header to break a site with. Start by telling the browser to report violations without blocking anything.

This policy suits a plain static site that loads everything from itself. Your site will need changes, such as allowing the domain of your analytics script.

Bash
sudo tee /etc/nginx/snippets/csp-report-only.conf > /dev/null <<'CONF'
add_header Content-Security-Policy-Report-Only "default-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always;
CONF
sudo sed -i '/security-headers.conf;/a\    include /etc/nginx/snippets/csp-report-only.conf;' /etc/nginx/conf.d/default.conf
sudo nginx -t
Bash
curl -sI http://localhost/ | grep -i content-security

The response has a Content-Security-Policy-Report-Only header. Open your site in a browser, open the developer tools console, and click through the main pages. Every resource the policy would have blocked is logged there, for example Refused to load the script ... because it violates the following Content Security Policy directive. Add each legitimate source to the policy, for example script-src 'self' https://analytics.example.com, until the console is quiet.

When it stays quiet for a few days of normal use, rename the header in the snippet from Content-Security-Policy-Report-Only to Content-Security-Policy. That switches it from watching to enforcing. Avoid 'unsafe-inline' and 'unsafe-eval' where you can, because they remove most of what CSP protects.

Step 5 · Add HSTS for HTTPS sites

HTTP Strict Transport Security tells a browser to use only HTTPS for your domain for a stated time. It stops a visitor from being downgraded to plain HTTP on a hostile network. Browsers only accept it from an HTTPS response, so it goes in the server block that listens on 443, not in the port-80 block and not in the shared snippet. Getting a certificate is covered in /tutorials/free-https-with-lets-encrypt-and-nginx.

Do this carefully. After a browser sees the header, it refuses plain HTTP for your domain until the time you set runs out. Lowering the value on the server only takes effect for browsers when they next visit and see the new header, so visitors who do not return keep the old rule. If HTTPS breaks on your site, visitors who saw the header cannot reach it. Start with a short time, and only raise it once you are sure that HTTPS works everywhere, including subdomains.

Start with five minutes. In your HTTPS server block, add:

Nginx
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    include /etc/nginx/snippets/security-headers.conf;
    add_header Strict-Transport-Security "max-age=300" always;
}

Note that this add_header sits at the server level, together with the include. If you also add a location that sets headers, the trap from earlier applies here too, unless you use add_header_inherit merge; or repeat the include there. Reload and check the response over HTTPS:

Bash
curl -sI https://example.com/ | grep -i strict-transport

The output is Strict-Transport-Security: max-age=300. Over the next weeks, raise it in steps, for example 86400 (one day), then 2592000 (30 days), then 31536000 (one year). Add includeSubDomains only when every subdomain serves HTTPS. Do not add preload unless you understand that it commits your domain to browser lists that are very hard to leave.

Step 6 · Test the result from outside

Run curl -I against your public address from your own computer. A scanner such as the Mozilla Observatory or securityheaders.com grades the same headers and explains each missing one. Treat the grade as a prompt to read, not a target: an A with a broken site is worse than a B that works.

Next steps

  • Serve the site over HTTPS: /tutorials/free-https-with-lets-encrypt-and-nginx.
  • Host more than one site on the server: /tutorials/host-multiple-sites-with-nginx-server-blocks.
  • Audit the server itself: /tutorials/audit-a-server-with-lynis.
  • The add_header rules are in the Nginx documentation for ngx_http_headers_module at nginx.org/en/docs/http/ngx_http_headers_module.html.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.