Blog

Adding CORS headers in Nginx without breaking caching

Use map directives for origins, separate location blocks for APIs, and Vary headers when needed.

1 min read
nginxinfrastructurecors

map $http_origin for allowlists

Centralize valid origins in a map and set $cors_origin only when the incoming Origin matches.

Avoid add_header duplication surprises by using always in the right server/location context.

Preflight and errors

Return 204 or 200 for OPTIONS with the same CORS headers you would send on success.

Ensure error pages from upstream still pass through your header injection or clients will see opaque failures.

Back to blog