basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ConfigHomelabnginx

    CORS and preflight OPTIONS in nginx: origin allowlist, cookies, and API errors

    Ready-to-use nginx CORS configs line by line: an origin allowlist via map, preflight OPTIONS returning 204, cookies and Authorization, hiding duplicate backend headers, and a separate rule for public fonts.

    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/ and https://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-Origin headers, 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.

    /etc/nginx/conf.d/02-cors-map.conf
    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;
    }
    Key part

    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.

    /etc/nginx/conf.d/api.example.org.conf
    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;
            }
    Key part

    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;
    Key part

    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:

    /etc/nginx/conf.d/static.example.org.conf (excerpt)
    location /fonts/ {
        root /var/www/static;
        add_header Access-Control-Allow-Origin "*" always;
        add_header Cache-Control "public, max-age=31536000, immutable" always;
    }
    Key part

    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

    1. Validate syntax and run a zero-downtime reload:
      sudo nginx -t && sudo systemctl reload nginx
    2. Test preflight OPTIONS from 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
    3. Test preflight from an unknown origin — neither Access-Control-Allow-Origin nor Access-Control-Allow-Credentials should 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
    4. Test a real request that returns an error (such as 401 without a token): Access-Control-Allow-Origin must appear exactly once and stay present on 401:
      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-Origin is missing the always flag: nginx attaches the header only to 2xx and 3xx responses and omits it on 4xx/5xx, so the browser masks the real HTTP status behind a CORS error.
    Fix
    Append always to every add_header inside location and inside if ($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 remaining proxy_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: * with Access-Control-Allow-Credentials: true.
    Fix
    Replace * with an exact origin allowlist via map $http_origin $cors_origin and echo $http_origin only 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 or proxy_cache stored one copy for the first requesting origin and served it to every other origin.
    Fix
    Add add_header Vary Origin always; wherever Access-Control-Allow-Origin is 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_header inside a location or if block cancels inheritance of all add_header directives from parent blocks (add_header inheritance).
    Fix
    Add include snippets/headers.conf; inside location /api/ alongside your CORS headers.