What CORS is and when to skip nginx
CORS (Cross-Origin Resource Sharing) is a browser security rule that stops scripts on one site from reading responses from another domain, scheme, or port unless the target server explicitly permits it with HTTP headers.
Only browsers enforce CORS — servers and curl ignore it. When a script on https://app.example.org calls fetch() against https://api.example.org, the origins differ. The browser still sends the request, yet withholds the response body from JavaScript unless the server returns Access-Control-Allow-Origin matching https://app.example.org.
When a request is not “simple” (it carries Authorization, Content-Type: application/json, or uses PUT, PATCH, DELETE), the browser first sends a preflight OPTIONS request with Origin, Access-Control-Request-Method, and Access-Control-Request-Headers. Until OPTIONS returns 204 with the expected allow headers, the actual request never reaches the app.
Skip configuring CORS in nginx when:
- The frontend and API share the same origin (
https://example.org/andhttps://example.org/api/) — no CORS headers are needed. - The backend app already sets CORS headers. Setting them in both layers produces duplicate
Access-Control-Allow-Originheaders, which browsers reject.
Handle CORS in nginx when multiple services sit behind one proxy (or a third-party backend has no origin allowlist): you maintain one allowlist in one place, and preflight OPTIONS requests terminate at the edge without hitting the app.
Origin allowlist via map
Old snippets often reflect the client header blindly (add_header Access-Control-Allow-Origin $http_origin;) or pair * with cookies. Reflecting any origin opens a cookie-authenticated API to every third-party website in the user’s browser; pairing * with credentials is rejected outright by browsers.
Use two map tables in the http context (for example in /etc/nginx/conf.d/02-cors-map.conf). This relies on built-in nginx behavior: when a variable passed to add_header evaluates to an empty string "", nginx omits the header completely. Unlisted origins receive neither Access-Control-Allow-Origin nor Access-Control-Allow-Credentials — with no nested if blocks.
map $http_origin $cors_origin {
default "";
"https://app.example.org" $http_origin;
"https://admin.example.org" $http_origin;
# Development only — leave commented out in production:
# "~^http://localhost:[0-9]+$" $http_origin;
}Exact allowlist of frontend origins. If the request Origin matches none of these lines, $cors_origin stays empty and nginx skips Access-Control-Allow-Origin. Enable the localhost regex only in development, never in production.
map $cors_origin $cors_creds {
"" "";
default "true";
}Second map enables Access-Control-Allow-Credentials: true only for origins that passed the allowlist. Unknown origins get an empty string, so the header is omitted.
Scenario 1: API with auth, cookies, and OPTIONS preflight
Below is a working block for an API behind a reverse proxy (Reverse proxy). Inside location /api/, nginx answers preflight OPTIONS with 204 No Content, strips any upstream CORS headers on real requests, and adds its own headers with always.
server {
listen 443 ssl;
http2 on;
server_name api.example.org;
# ssl_certificate / ssl_certificate_key / snippets/tls.conf
location /api/ {Accept traffic on the API domain (built on top of the HTTPS config from HTTPS & HTTP/3). The /api/ block handles both preflight and proxied requests.
if ($request_method = OPTIONS) {
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Credentials $cors_creds 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" always;
add_header Access-Control-Max-Age 86400 always;
add_header Vary Origin always;
return 204;
}Handle preflight OPTIONS before proxying upstream. if with return 204; is one of the two safe ways to use if inside location (if inside location). add_header directives from location are not inherited inside if, so declare every required header explicitly here. Access-Control-Max-Age 86400 caches preflight responses in the browser (Firefox honors up to 24 hours; Chromium caps it at 2 hours).
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;
proxy_hide_header Access-Control-Expose-Headers;Strip any CORS headers the backend might send. Without these lines, the browser sees two Access-Control-Allow-Origin headers and blocks the response.
include snippets/headers.conf;
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Credentials $cors_creds always;
add_header Access-Control-Expose-Headers "X-Request-Id, Content-Disposition" always;
add_header Vary Origin always;Headers for actual GET/POST/PUT/DELETE requests. always is required: without it, nginx drops Access-Control-Allow-Origin on 401, 403, 422, and 500, hiding the real API error behind a CORS failure. Access-Control-Expose-Headers lets frontend JS read custom headers. Vary: Origin prevents caches from mixing responses across origins.
include snippets/proxy-headers.conf;
proxy_set_header Connection "";
proxy_pass http://127.0.0.1:3000;
}
}Standard upstream proxying with the proxy headers snippet from Reverse proxy.
Scenario 2: public fonts and static assets on a subdomain
Browsers always fetch web fonts (.woff2) in CORS mode: without Access-Control-Allow-Origin, fonts hosted on static.example.org fail to load. Cookies and Authorization are not sent here, so * is safe and needs neither map nor Vary: Origin:
location /fonts/ {
root /var/www/static;
add_header Access-Control-Allow-Origin "*" always;
add_header Cache-Control "public, max-age=31536000, immutable" always;
}Allow any origin (*) for public fonts and set a long browser cache on content-hashed files. Do not set Access-Control-Allow-Credentials here.
How to check
- Validate syntax and run a zero-downtime reload:
sudo nginx -t && sudo systemctl reload nginx - Test preflight
OPTIONSfrom an allowed origin:curl -sS -i -X OPTIONS \ -H "Origin: https://app.example.org" \ -H "Access-Control-Request-Method: POST" \ -H "Access-Control-Request-Headers: Authorization, Content-Type" \ https://api.example.org/api/health # HTTP/2 204 # access-control-allow-origin: https://app.example.org # access-control-allow-credentials: true # access-control-allow-methods: GET, POST, PUT, PATCH, DELETE, OPTIONS # access-control-allow-headers: Authorization, Content-Type, X-Requested-With # access-control-max-age: 86400 # vary: Origin - Test preflight from an unknown origin — neither
Access-Control-Allow-OriginnorAccess-Control-Allow-Credentialsshould appear:curl -sS -i -X OPTIONS \ -H "Origin: https://evil.example.net" \ -H "Access-Control-Request-Method: POST" \ https://api.example.org/api/health # HTTP/2 204 — no Access-Control-Allow-Origin or Access-Control-Allow-Credentials lines - Test a real request that returns an error (such as
401without a token):Access-Control-Allow-Originmust appear exactly once and stay present on401:curl -sS -i -H "Origin: https://app.example.org" https://api.example.org/api/profile \ | grep -iE '^(HTTP/|access-control-|vary:)' # HTTP/2 401 # access-control-allow-origin: https://app.example.org # access-control-allow-credentials: true # access-control-expose-headers: X-Request-Id, Content-Disposition # vary: Origin
If it doesn’t work
Browser console shows CORS error, while curl returns 401 Unauthorized or 500 Internal Server Error
- Cause
add_header Access-Control-Allow-Originis missing thealwaysflag: nginx attaches the header only to2xxand3xxresponses and omits it on4xx/5xx, so the browser masks the real HTTP status behind a CORS error.- Fix
- Append
alwaysto everyadd_headerinsidelocationand insideif ($request_method = OPTIONS).
Browser logs The 'Access-Control-Allow-Origin' header contains multiple values
- Cause
- Both the application (for example Express or FastAPI middleware) and nginx are adding
Access-Control-Allow-Origin. Browsers accept only a single value. - Fix
- Manage CORS in one place only. When nginx owns it, strip upstream copies with
proxy_hide_header Access-Control-Allow-Origin;and the remainingproxy_hide_header Access-Control-*directives.
Requests with cookies (credentials: 'include') or Authorization fail with a wildcard * error
- Cause
- The CORS specification forbids combining
Access-Control-Allow-Origin: *withAccess-Control-Allow-Credentials: true. - Fix
- Replace
*with an exact origin allowlist viamap $http_origin $cors_originand echo$http_originonly for approved domains.
Frontend on admin.example.org gets a cached response with Access-Control-Allow-Origin: https://app.example.org and the browser blocks it
- Cause
- Without
Vary: Origin, a CDN orproxy_cachestored one copy for the first requesting origin and served it to every other origin. - Fix
- Add
add_header Vary Origin always;whereverAccess-Control-Allow-Originis populated dynamically from$http_origin.
Frontend cannot read custom response headers like X-Request-Id or Content-Disposition via response.headers.get(...)
- Cause
- Browsers expose only seven CORS-safelisted response headers to scripts by default and hide everything else.
- Fix
- List the extra headers in
add_header Access-Control-Expose-Headers "X-Request-Id, Content-Disposition" always;.
After adding CORS to location /api/, Strict-Transport-Security and other server-level security headers disappeared
- Cause
- Any
add_headerinside alocationorifblock cancels inheritance of alladd_headerdirectives from parent blocks (add_header inheritance). - Fix
- Add
include snippets/headers.conf;insidelocation /api/alongside your CORS headers.