Home About Me

How to Allow CORS for Several Specific Sites in Nginx

When configuring CORS in Nginx, the most straightforward option is to allow requests from anywhere:

add_header Access-Control-Allow-Origin *;

That opens cross-origin access to all websites.

If you only want to permit a single site, you can set a specific origin instead:

add_header Access-Control-Allow-Origin https://www.psay.cn;

The problem appears when you need to allow several specific sites. Nginx does not support listing multiple URLs directly after Access-Control-Allow-Origin. In practice, that means you cannot simply place several domains there. The header can either allow all origins with *, or return one specific origin.

A simple workaround is to check the incoming Origin value and assign it only when it matches one of the allowed sites. Add the following inside server{}:

set $cors_origin "";
if ($http_origin ~* "^http://test.blyoo.com$") {
  set $cors_origin $http_origin;
}
if ($http_origin ~* "^https://www.blyoo.com$") {
  set $cors_origin $http_origin;
}
add_header Access-Control-Allow-Origin $cors_origin;

With this approach, only requests coming from the matched domains will receive the corresponding Access-Control-Allow-Origin header, which makes it possible to support multiple approved websites without opening access to everyone.