Reverse Proxy · add_header ... always

Nginx CORS Preflight Config: map $http_origin & add_header always Pitfalls

Configure Nginx reverse-proxy CORS safely using map $http_origin, the always directive on 204/4xx/5xx responses, and Vary: Origin without breaking header inheritance.

Zero Telemetry · Strict CSP (connect-src 'none')

CORS Policy & Preflight Controls

Access-Control-Allow-Methods
Simulate Browser Preflight Request (OPTIONS)
CORS Security & Fetch Spec Linter
100 / 100
PASS

Pass: 3 · Warnings: 0 · Errors: 0

CORS-002: Strict origin allowlist (2 origins) PASS
https://app.example.com, https://studio.example.com
CORS-004: Vary: Origin cache safety enabled PASS
Prevents CDN/proxy cache poisoning across distinct allowed origins.
CORS-005: Access-Control-Max-Age (7200s) within Chromium 7200s cap PASS
Avoids unnecessary OPTIONS preflight round-trips while honoring cross-browser cache ceilings.
Simulated Preflight Response
# Simulated Browser Preflight: OPTIONS /api/v1/resource
# Request Origin: https://app.example.com | Method: POST | Headers: Authorization, Content-Type
# Browser Verdict: ALLOWED (HTTP 204 No Content)

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Authorization, Content-Type, X-Requested-With, Idempotency-Key
Access-Control-Expose-Headers: X-Request-Id, X-RateLimit-Remaining
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 7200
Vary: Origin

Copy-Paste Runtime Configs (6 Stacks)

Nginx (cors.conf)
map $http_origin $cors_origin {
    default "";
    "https://app.example.com" "https://app.example.com";
    "https://studio.example.com" "https://studio.example.com";
}
location /api/ {
    add_header Access-Control-Allow-Origin $cors_origin always;
    add_header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS" always;
    add_header Access-Control-Allow-Headers "Authorization, Content-Type, X-Requested-With, Idempotency-Key" always;
    add_header Access-Control-Expose-Headers "X-Request-Id, X-RateLimit-Remaining" always;
    add_header Access-Control-Allow-Credentials "true" always;
    add_header Access-Control-Max-Age "7200" always;
    add_header Vary "Origin" always;

    if ($request_method = 'OPTIONS') {
        return 204;
    }
    proxy_pass http://127.0.0.1:8080;
}
Live API & Edge Audit Zero-Upload SpecDiff

Harden your live domain headers, OpenAPI schemas & AEO discovery

Test your deployed domain's security headers, HSTS, CSP & DMARC live on ReadyCheck, diff OpenAPI contracts & OWASP API Top 10 risks in SpecDiff, or deploy all 9 production configs in minutes with the $49 ReadyCheck Fix Pack.

Protocol Rules & Header Reference

Rule / Header Production Value Behavior & Gotchas
add_header ... always Mandatory on 204 / 4xx / 5xx Without always, Nginx drops CORS headers on 204, 401, 403, and 502 responses
map $http_origin $cors_origin Exact allowlist lookup Safer and cleaner than nested if ($http_origin ~* ...) blocks
add_header Inheritance Trap Any add_header in if() wipes parent headers Never put add_header inside if ($request_method = OPTIONS) without repeating all headers
Vary: Origin add_header Vary "Origin" always; Critical when sitting behind CloudFront, Cloudflare, or Fastly

Hardened Nginx server/location CORS Block (map + always)

nginx-cors.conf
map $http_origin $cors_origin {
    default "";
    "https://app.example.com" "https://app.example.com";
    "https://admin.example.com" "https://admin.example.com";
}

server {
    listen 443 ssl http2;
    server_name api.example.com;

    location /api/ {
        if ($request_method = 'OPTIONS') {
            add_header Access-Control-Allow-Origin $cors_origin always;
            add_header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS" always;
            add_header Access-Control-Allow-Headers "Authorization, Content-Type, Idempotency-Key" always;
            add_header Access-Control-Allow-Credentials "true" always;
            add_header Access-Control-Max-Age "7200" always;
            add_header Vary "Origin" always;
            add_header Content-Length 0;
            return 204;
        }

        add_header Access-Control-Allow-Origin $cors_origin always;
        add_header Access-Control-Allow-Credentials "true" always;
        add_header Access-Control-Expose-Headers "X-Request-Id" always;
        add_header Vary "Origin" always;
        proxy_pass http://127.0.0.1:8080;
    }
}

Avoid Duplicate Header Collisions with Upstream App

nginx-dedup.conf
# If your upstream Node/Python app ALSO emits CORS headers, hide upstream headers
# in Nginx so browsers do not reject duplicate Access-Control-Allow-Origin headers:
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Credentials;
proxy_hide_header Access-Control-Allow-Methods;
proxy_hide_header Access-Control-Allow-Headers;

Key Engineering Takeaways

  • Nginx's add_header directive silently drops headers on HTTP 204, 400, 401, 403, and 500 responses unless the always keyword is appended.
  • Using map $http_origin $cors_origin returns an empty string for unlisted origins, causing Nginx to omit Access-Control-Allow-Origin cleanly (because Nginx ignores add_header when the value evaluates to empty).
  • If both Nginx and an upstream Express/FastAPI backend emit Access-Control-Allow-Origin, browsers fail immediately due to multiple Access-Control-Allow-Origin header values.

Common Production Pitfalls to Avoid

  • Writing add_header in a child if () block causes Nginx to discard EVERY add_header inherited from the parent location/server block (IfIsEvil quirk).
  • Forgetting proxy_hide_header when migrating CORS from backend middleware to Nginx creates duplicate comma-joined Allow-Origin headers.
  • Using regex ~* example\.com in map without ^https:// anchors lets https://evil-example.com pass.

More CORS & Webhook Signature Guides

← Back to CORS & Webhook HMAC Debugger Hub · OpenAPI OWASP API Top 10 & MCP Scorer → · SBOM & Sigstore Validator → · HTTP Security Headers & CSP →

Frequently Asked Questions

Why does Nginx return 204 OPTIONS with zero CORS headers?

By default Nginx only runs add_header on 200, 201, 204 (not always in older setups), 206, 301-308, or when an inner if block overrides parent add_header directives. Always specify add_header ... always directly inside the OPTIONS branch or use OpenResty/NJS.

What happens if both Nginx and FastAPI send Access-Control-Allow-Origin?

Browsers abort the fetch with 'The Access-Control-Allow-Origin header contains multiple values'. Set CORS in one layer only, or add proxy_hide_header in Nginx.

Can I verify my live Nginx security + CORS headers together?

Use /security-headers/nginx/ to harden HSTS/CSP alongside Nginx CORS, then scan your live endpoint on audit.runglab.dev.