webzod
account

Limit CORS to the origins that need it on nginx

headers.cors.reflected_origin · effort: about an hour

Why it matters

The server echoes any Origin, so every website can read these responses from a visitor's browser, which matters as soon as a response holds anything not meant for everyone. A fixed allow-list, or no CORS headers at all when nothing needs them, keeps that in check.

Staged change. Do this in stages and check each one before the next, so a mistake does not break your site or your mail.

The fix

  1. Stage 1: replace add_header Access-Control-Allow-Origin $http_origin with the map below (http context), listing your real origins. If the application sets the header itself, hide its copy with proxy_hide_header (or fastcgi_hide_header for PHP-FPM) so only nginx's copy is sent.
  2. Put these lines in the server block, or in a location that already includes your shared security-headers snippet. add_header and proxy_hide_header lines in a location replace the server-level ones (nginx 1.29.3 and later can use add_header_inherit merge; for add_header).
  3. Stage 2: run sudo nginx -t, reload and test the sites that call you. An empty value means nginx does not send the header.
nginx
# http {} context
map $http_origin $cors_allow_origin {
    default "";
    "https://app.example.com" $http_origin;
}

# server {} block (or a location that already includes your security headers)
proxy_hide_header Access-Control-Allow-Origin;
add_header Access-Control-Allow-Origin $cors_allow_origin always;
add_header Vary Origin always;

The examples use example.com. Replace it with your own domain.

Read the documentation (opens in a new tab)

Scan your domain to see whether this applies to you.