Chapter 10 · Lesson 8 of 10
Server security

TLS and HTTP security headers checklist for nginx and Caddy

A TLS and security header checklist sets modern protocol versions and response headers that tell browsers to use HTTPS, avoid sniffing content types and limit framing and scripts.

By the end you will

Apply and verify a set of TLS settings and security headers in nginx or Caddy, and avoid the add_header inheritance trap.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • A website already served over HTTPS
  • nginx or Caddy with sudo access

A site that works over HTTPS still leaves choices to the browser. Security headers make those choices explicit: use only HTTPS, do not guess content types, do not let other sites frame you, and load scripts only from places you name. The list below is a checklist you can apply in nginx or Caddy and verify with curl. Treat it as a starting point and test your own pages, because a strict header can break a working site.

How it works#

The server adds headers to every response. Browsers read them and apply rules: HSTS makes the browser refuse plain HTTP for your domain, CSP limits where content may load from, nosniff stops content type guessing, and so on. None of this changes what your app does. It only adds browser-side limits that reduce the damage of mistakes such as a downgrade attack, an injected script or a clickjacking frame.

TLS settings work one layer below, in the handshake. They decide which protocol versions and ciphers the server will accept. Modern defaults are good, so the work is mostly to avoid weakening them. Background: TLS versions and ciphers and HSTS explained.

Step 1: Allow only TLS 1.2 and 1.3#

In nginx, in the http or server block:

nginx
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;

Leave the cipher list at its default unless you have a specific reason, since current defaults are sound. Caddy already uses TLS 1.2 and 1.3 with safe defaults and needs no setting. Check what a server negotiates with openssl s_client -connect example.com:443 -tls1_2, as in inspect a TLS certificate with OpenSSL.

Step 2: Add HSTS carefully#

nginx
add_header Strict-Transport-Security "max-age=300" always;

Start with a short max-age (300 seconds here), check that everything works, then raise it, for instance to a year. Two optional parts need care. includeSubDomains applies the rule to every subdomain, so one HTTP-only internal host breaks. preload asks browsers to ship your domain in their built-in list, which is slow and difficult to reverse. Do not add either until you are sure.

Step 3: Add the simple headers#

nginx
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header X-Frame-Options "SAMEORIGIN" always;

nosniff stops content type guessing. Referrer-Policy limits what URL information goes to other sites. Permissions-Policy turns off browser features your site does not use, so adjust the list for your app. X-Frame-Options is the older clickjacking control. The modern one is frame-ancestors in CSP.

Step 4: Add a Content-Security-Policy, in report-only mode first#

nginx
add_header Content-Security-Policy-Report-Only "default-src 'self'; frame-ancestors 'self'" always;

default-src 'self' allows resources only from your own origin. Real sites need more, such as a CDN for scripts or inline styles, so the first policy will log violations in the browser console. Open the site, read the console, add the sources you need, and when the console is quiet, rename the header to Content-Security-Policy to enforce. Avoid 'unsafe-inline' for scripts if you can. A policy that is too loose gives little protection, and one that is too strict breaks pages, which is why report-only comes first.

Step 5: The nginx add_header inheritance trap#

This catches nearly everyone:

nginx
server {
    add_header X-Content-Type-Options "nosniff" always;

    location /api/ {
        add_header Cache-Control "no-store";
        proxy_pass http://127.0.0.1:3000;
    }
}

Inside /api/, the nosniff header is gone. nginx inherits add_header from the level above only when the current level defines none of its own. Fix it by repeating the headers in the location, or by putting them in a snippet and including it at every level:

nginx
include /etc/nginx/snippets/security-headers.conf;

Also use always. Without it nginx adds the header only on success and redirect codes, so error pages like 404 and 502 go out without it. Validate and reload:

bash
sudo nginx -t && sudo systemctl reload nginx

Step 6: The same in Caddy#

Caddy sets headers with the header directive:

output
example.com {
    header {
        Strict-Transport-Security "max-age=300"
        X-Content-Type-Options "nosniff"
        Referrer-Policy "strict-origin-when-cross-origin"
        Permissions-Policy "camera=(), microphone=(), geolocation=()"
        Content-Security-Policy-Report-Only "default-src 'self'; frame-ancestors 'self'"
        -Server
    }
    reverse_proxy 127.0.0.1:3000
}

The -Server line removes the Server header. Check the file with caddy validate --config /etc/caddy/Caddyfile and reload with sudo systemctl reload caddy. See Caddy from scratch for the basics, and rate limiting and security headers for limits that sit next to these.

Check it worked#

bash
curl -sI https://example.com
curl -sI https://example.com/does-not-exist
curl -sI http://example.com

The first shows your headers. The second checks that headers appear on error pages (the always flag). The third should redirect to HTTPS. Verify each page type, including proxied paths such as /api/, because the inheritance trap hides there.

Edge cases and gotchas#

  • Duplicate headers. If your app and your proxy both set a header, the browser may see two values. Set it in one place.
  • HSTS lasts. Browsers cache it for the max-age. You cannot undo it for a browser that already saw it. Raise the age in steps.
  • CSP and inline code. Frameworks that inject inline scripts need nonces or hashes. Watch the console in report-only mode.
  • Redirects. HSTS is only honored over HTTPS. A header sent on the HTTP redirect is ignored.
  • Cached responses. A CDN may cache old headers. Purge it after a change.
  • Header lists get stale. Check MDN or OWASP when you revisit the list, because recommendations change over time.

Troubleshooting#

SymptomLikely causeFix
Header missing on some pathsadd_header inheritance in a locationUse an include file at every level
Header missing on 404 or 502No always flagAdd always
Page broken after enabling CSPPolicy blocks needed sourcesUse report-only, add sources, then enforce
nginx: [emerg] unknown directiveTypo or missing moduleFix the line, run nginx -t
Browser forces HTTPS on a test hostHSTS cached for the domainUse a different hostname for tests
Two Strict-Transport-Security linesSet in app and proxyRemove one
SSL_ERROR_NO_CYPHER_OVERLAP for old clientsThey only support old TLSExpected, those clients are unsupported

Quick reference#

nginx
ssl_protocols TLSv1.2 TLSv1.3;
add_header Strict-Transport-Security "max-age=300" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy-Report-Only "default-src 'self'; frame-ancestors 'self'" always;
bash
curl -sI https://example.com
sudo nginx -t && sudo systemctl reload nginx

Next#

Continue with Audit a Linux server.

Check what you learned4 questions
1In nginx, a location block contains one add_header line. What happens to add_header lines in the server block?
2What does X-Content-Type-Options: nosniff do?
3Why start Content-Security-Policy as report-only?
4Which header controls who may embed your page in a frame in modern browsers?

Frequently asked questions

Which TLS versions should a server allow?

TLS 1.2 and TLS 1.3. Older versions such as TLS 1.0 and 1.1 are deprecated and should be disabled. Current nginx and Caddy defaults already follow this when you use a recent version.

Is it safe to turn on HSTS?

It is safe once all your subdomains work over HTTPS, but browsers remember it for the max-age you set. Start with a short max-age, then raise it. Be careful with includeSubDomains and preload, which are hard to undo.

Why did my nginx security headers disappear?

nginx add_header directives are inherited only if the current level defines none. A single add_header in a location block discards every add_header from the server block above it.

How do I test headers from the command line?

Run curl -I https://example.com and read the response headers. Use -s -D - -o /dev/null to print headers only and add -L to follow redirects.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios