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:
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.
1Map Explicit Allowed Origins Safely at the http Block Level
/etc/nginx/conf.d/cors-map.confNever 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.confnginxmap $http_origin $cors_origin { default ""; "https://app.example.com" "https://app.example.com"; "http://localhost:5173" "http://localhost:5173"; }2Handle OPTIONS Preflights With 204 and Strip Upstream Duplicate Headers
/etc/nginx/conf.d/api.confUse 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.confnginxupstream 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; } }3Forward Origin Cleanly When Delegating CORS to the Upstream Container
/etc/nginx/conf.d/api-passthrough.confAlternatively, 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.confnginxlocation /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; }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)bashdocker 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.
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.
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.
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.
Deploying Behind Nginx? Eliminate CORS Preflights or Configure Your 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).
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.
Related CORS Stack Simulators
Browse all 12 stacks →Laravel Sanctum SPA Cookie Auth CORS Simulator & Fix Guide
Fix Laravel Sanctum SPA cookie CORS errors. Validate supports_credentials, SANCTUM_STATEFUL_DOMAINS, X-XSRF-TOKEN preflight headers, and SameSite rules.
FastAPI + Next.js CORS Config Simulator & Fix Guide
Fix CORS preflight failures between Python FastAPI (Uvicorn) and Next.js on port 3000. Configure CORSMiddleware order, trailing redirects, and credentials.
ASP.NET Core 8/9 + Angular CORS Config Simulator & Fix Guide
Fix CORS errors between ASP.NET Core 8/9 Web API and Angular CLI on port 4200. Verify UseCors middleware ordering, AllowCredentials, and HTTPS redirects.
Cloudflare Workers API + SPA Frontend CORS Simulator & Fix Guide
Fix CORS preflight failures between Cloudflare Workers APIs and static SPAs on Pages, Vercel, or Netlify. Handle OPTIONS 204, immutable headers, and Vary.