fix(security): keep all headers on auth routes in the Nginx example

The Senior SecOps Engineer's "HTTP Security Headers (Nginx)" snippet puts
Cache-Control inside `location /api/auth/`. nginx inherits server-level
add_header directives only when the child level declares none, so that one
nested add_header drops HSTS, X-Content-Type-Options, X-Frame-Options,
Referrer-Policy, Permissions-Policy and CSP on exactly the auth routes —
the paths the example exists to protect.

Verified with nginx 1.27.4 (official Windows build): GET /api/auth/login
returned only `Cache-Control: no-store` while / returned all six security
headers. Scope no-store with a map at the server level instead, so every
header stays in one place; /api/auth/ still gets no-store and other routes
omit Cache-Control.

Checks: lint 0 errors / 0 warnings, originality PASSED, converter contract
32 passed / 0 failed (282 agents x 15 tools) with only this agent's
expected advisory drift; `nginx -t` clean.
This commit is contained in:
马建彤
2026-10-16 10:40:20 +08:00
parent 652b2692f8
commit 7209091dfc
+15 -4
View File
@@ -423,6 +423,15 @@ res.json({ message: "Authenticated" }); // NO token in body
### HTTP Security Headers (Nginx)
```nginx
# add_header directives are inherited from the parent level only when the child
# level declares none, so putting Cache-Control in a nested location would drop
# every security header above on exactly the auth routes. Apply it at the server
# level through a map instead (map lives in the http block).
map $uri $cache_control {
~^/api/auth/ "no-store";
default "";
}
server {
# Force HTTPS (1 year + subdomains + preload)
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
@@ -442,13 +451,15 @@ server {
# CSP — adjust script/style sources to match your CDNs
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none';" always;
# No-cache for auth routes
location /api/auth/ {
add_header Cache-Control "no-store" always;
}
# No-cache for auth routes (empty elsewhere, so the header is omitted there)
add_header Cache-Control $cache_control always;
# Remove server version
server_tokens off;
location /api/auth/ {
# auth handlers; no add_header here — see the map above
}
}
```