CORS & Preflight Simulator · Nginx Reverse Proxy + SPA + Docker API

Nginx Reverse Proxy + Docker API CORS Simulator & Fix Guide

Simulate Fetch Standard preflight (OPTIONS) triggers, credential rules, and origin matching between SPA + Docker API and Nginx Reverse Proxy. Copy generated configuration code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Browser Request (SPA + Docker API)

2. Server Response Policy (Nginx Reverse Proxy)

Access-Control-Allow-Methods
# nginx.conf — Reverse Proxy CORS Block
# IMPORTANT: Disable CORS headers in your upstream app (or proxy_hide_header)
# to avoid duplicate 'Access-Control-Allow-Origin' headers.

location /api/ {
    # Handle CORS Preflight (OPTIONS) directly at the gateway
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' 'https://app.example.com' always;
        add_header 'Access-Control-Allow-Credentials' 'true' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, PATCH, DELETE, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization' always;
        add_header 'Access-Control-Max-Age' 86400 always;
        add_header 'Vary' 'Origin' always;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
    }

    # Strip upstream CORS headers if the backend also emits them
    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;

    # Apply CORS headers to actual responses (including 4xx/5xx via 'always')
    add_header 'Access-Control-Allow-Origin' 'https://app.example.com' always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Vary' 'Origin' always;

    proxy_pass http://api_upstream;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

Preflight (OPTIONS)

Triggered · Passed

Content-Type "application/json" is not CORS-safelisted (only application/x-www-form-urlencoded, multipart/form-data, and text/plain avoid preflight). Request includes non-safelisted header(s): Authorization.

Browser Verdict

Allowed

Browser CORS validation passed. JavaScript can read the response body.

Rule Engine Diagnostics

  • Reverse Proxy Tip: Avoid Duplicate CORS Headers in Nginx + Upstream App

    Never configure Access-Control-Allow-Origin in both Nginx and your backend framework simultaneously. Browsers reject duplicate headers with: "The 'Access-Control-Allow-Origin' header contains multiple values '*, https://app.example.com', but only one is allowed." Choose one layer (or use proxy_hide_header in Nginx).

Simulated HTTP Response Headers

HTTP/1.1
Preflight (OPTIONS)
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: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Actual Response (POST)
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Vary: Origin

Runs locally in your browser. Origins, endpoints, and headers are never sent to a server.

Typical Browser Console Error (SPA + Docker API → Nginx Reverse Proxy)

When cross-origin headers are missing, mismatched, or blocked during preflight between SPA + Docker API and Nginx Reverse Proxy, Chrome and Firefox log an error matching the pattern below in DevTools:

DevTools Console Output

Access to fetch at 'https://api.example.com/api/v1/reports' from origin 'https://app.example.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, https://app.example.com', but only one is allowed.

Why CORS Blocks Requests Between SPA + Docker API and Nginx Reverse Proxy

Placing an Nginx reverse proxy in front of Dockerized backend containers (Laravel PHP-FPM, FastAPI/Uvicorn, Express, or Go services) is standard production infrastructure, yet it introduces three notorious Nginx-specific CORS pitfalls that almost never surface on localhost. The most common failure is the duplicate header collision: both Nginx and the upstream Docker container emit Access-Control-Allow-Origin, causing browsers to immediately reject the response with "contains multiple values, but only one is allowed."

The second classic Nginx trap is omitting the always parameter on add_header directives. By default, Nginx ONLY attaches add_header directives to 200, 201, 204, 206, 301, 302, 303, 304, 307, and 308 responses. Whenever your Docker API returns a 400 Bad Request, 401 Unauthorized, 422 Validation Error, or 502 Bad Gateway during a container restart, Nginx silently omits Access-Control-Allow-Origin; turning every API validation error into an unreadable browser CORS failure.

The third trap is Nginx's strict add_header inheritance behavior: defining ANY add_header directive inside a nested if ($request_method = 'OPTIONS') or location block wipes out all add_header directives declared in parent server or http blocks. Mastering these three rules, alongside proxy_hide_header and map-based origin allowlists, prevents hours of chasing phantom CORS failures in production Docker deployments.

In production Docker Compose or Kubernetes ingress environments, document clearly in your repository whether Nginx or the upstream application container owns CORS headers so future pull requests never reintroduce duplicate Access-Control-Allow-Origin values. Whenever Nginx acts as the authoritative gateway, pair map-based origin whitelisting with proxy_hide_header for all four Access-Control-Allow-* headers and verify that every add_header directive ends with the always keyword. Testing both healthy 200 responses and intentionally forced 401, 422, and 502 responses guarantees your frontend error handlers remain fully functional even during upstream outages.

Step-by-Step Nginx Reverse Proxy + SPA + Docker API CORS Fix Guide

Follow each step below in order to eliminate preflight failures and lock down production origins safely for Nginx Reverse Proxy.

  1. 1Map Explicit Allowed Origins Safely at the http Block Level

    /etc/nginx/conf.d/cors-map.conf

    Never echo $http_origin blindly into Access-Control-Allow-Origin, which allows any malicious website to steal authenticated responses. Use an Nginx map block at the http context level to whitelist exact frontend origins so untrusted origins evaluate to an empty string and emit zero CORS headers.

    /etc/nginx/conf.d/cors-map.confnginx
    map $http_origin $cors_origin {
        default "";
        "https://app.example.com" "https://app.example.com";
        "http://localhost:5173"   "http://localhost:5173";
    }
  2. 2Handle OPTIONS Preflights With 204 and Strip Upstream Duplicate Headers

    /etc/nginx/conf.d/api.conf

    Use proxy_hide_header to strip any CORS headers emitted by the Dockerized backend container so Nginx acts as the single authoritative CORS gateway. Always append the always keyword to every add_header directive so 4xx and 5xx error responses remain readable by your frontend.

    /etc/nginx/conf.d/api.confnginx
    upstream api_upstream {
        server api_container:8000;
    }
    
    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-Credentials' 'true' always;
                add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, PATCH, DELETE, OPTIONS' always;
                add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization' always;
                add_header 'Access-Control-Max-Age' 86400 always;
                add_header 'Vary' 'Origin' always;
                add_header 'Content-Type' 'text/plain; charset=utf-8';
                add_header 'Content-Length' 0;
                return 204;
            }
    
            # Prevent duplicate CORS headers if the Docker backend also emits them
            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;
    
            add_header 'Access-Control-Allow-Origin' $cors_origin always;
            add_header 'Access-Control-Allow-Credentials' 'true' always;
            add_header 'Vary' 'Origin' always;
    
            proxy_pass http://api_upstream;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
  3. 3Forward Origin Cleanly When Delegating CORS to the Upstream Container

    /etc/nginx/conf.d/api-passthrough.conf

    Alternatively, if you prefer letting Laravel, FastAPI, or Express manage CORS directly inside application code, remove ALL add_header Access-Control-* lines from Nginx and verify that Nginx forwards the Origin header untouched and allows OPTIONS requests through to the upstream container.

    /etc/nginx/conf.d/api-passthrough.confnginx
    location /api/ {
        # Passthrough mode: let the Docker backend own all CORS headers
        proxy_pass http://api_upstream;
        proxy_set_header Host $host;
        proxy_set_header Origin $http_origin;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
  4. 4Test Both 200 and 401/422 Responses With curl Through Nginx

    terminal (Docker host)

    Validate syntax with nginx -t, reload cleanly with zero downtime, and inspect raw HTTP headers for both an OPTIONS preflight and an intentionally unauthorized POST (401) to confirm exactly one Access-Control-Allow-Origin header is present in every scenario.

    terminal (Docker host)bash
    docker exec nginx_gateway nginx -t && docker exec nginx_gateway nginx -s reload
    
    # Verify preflight (expect 204 + single Access-Control-Allow-Origin)
    curl -i -X OPTIONS https://api.example.com/api/v1/reports \
      -H "Origin: https://app.example.com" \
      -H "Access-Control-Request-Method: POST" \
      -H "Access-Control-Request-Headers: content-type, authorization"

Common Nginx Reverse Proxy + SPA + Docker API CORS Pitfalls

Even when your basic origin string looks correct, these three framework-specific edge cases frequently reintroduce CORS failures in staging and production environments.

Pitfall 1

Duplicate Access-Control-Allow-Origin From Nginx + Backend Framework

Leaving Laravel HandleCors or FastAPI CORSMiddleware active while also adding add_header Access-Control-Allow-Origin in Nginx emits two headers. Browsers immediately block the response. Either own CORS exclusively in Nginx (with proxy_hide_header) or exclusively in the upstream app.

Pitfall 2

Forgetting the "always" Keyword on add_header Directives

Without the always parameter, Nginx omits CORS headers on 400, 401, 403, 404, 422, and 500 responses. Your React or Angular app then cannot read validation error messages from the backend and reports a generic network/CORS failure instead.

Pitfall 3

add_header Inside a Location or If Block Wiping Parent Security Headers

In Nginx, adding even a single add_header inside a location or if block disables inheritance of all add_header directives (such as Strict-Transport-Security or X-Content-Type-Options) from the enclosing server block. Repeat necessary headers inside the block or include a shared snippet file.

Related Tool · Same-Origin Reverse Proxy

Configure TLS, WebSocket headers, and X-Forwarded-Proto, or serve your frontend and /api/ on the same origin with Nginx Reverse Proxy for Docker Compose Services (127.0.0.11 DNS Resolver).

Open Nginx Builder

Frequently Asked Questions

Should Nginx or my Docker backend framework handle CORS?
If Nginx proxies multiple heterogeneous microservices (for example, a Python service and a Node service behind one gateway), handling CORS centrally in Nginx with proxy_hide_header guarantees uniform rules; including when a container crashes with 502 Bad Gateway. For single-backend apps like Laravel Sanctum, letting the app handle CORS while Nginx stays in pure passthrough mode is often simpler.
Why does Nginx say "always" is invalid or not work on older configs?
The always parameter has been supported since Nginx 1.7.5. Make sure it is placed at the very end of the add_header line right before the semicolon: add_header 'Access-Control-Allow-Origin' $cors_origin always;.
What happens if $cors_origin evaluates to an empty string in Nginx?
Nginx automatically omits any add_header directive whose evaluated value is an empty string. This makes the map $http_origin $cors_origin pattern ideal because disallowed origins receive no Access-Control-Allow-Origin header at all.
Why do I get a CORS error when my Docker container is restarting?
When the upstream container is unavailable, Nginx generates a 502 Bad Gateway or 504 Gateway Timeout directly. Unless your Nginx location block uses add_header .. always, those gateway error responses lack CORS headers and show up as CORS errors in browser DevTools.
Browse all 12 stacks →