Nginxで複数のAccess-Control-Allow-Originとpreflightに対応する方法
やり方
複数のAccess-Control-Allow-Originヘッダーを出すことはできないので、mapディレクティブで複数のAccess-Control-Allow-Originのドメインを動的に変更する。
CORSとpreflightについての詳しい説明は割愛します。
なお、あくまで例です。
詳細な設定はきちんと調べましょう。
例
許可するドメインと一致した場合に$cors変数に$http_originをmapします。
nginx.conf
map $http_origin $cors{
"https://external01.example.com" $http_origin;
"https://external02.example.org" $http_origin;
}
location / {
root /var/html;
try_files $uri /index.html;
index index.html;
# preflight対応
include conf.d/pf.conf;
}
## SNIP ##
add_header Access-Control-Allow-Origin $cors always;
add_header Access-Control-Allow-Credentials true;
preflight対応のincludeファイル
pf.conf
# preflight対応
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin $cors;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
add_header Access-Control-Allow-Headers '*';
add_header Access-Control-Max-Age 7200;
add_header Content-Type 'text/plain charset=UTF-8';
add_header Content-Length 0;
return 204;
}