LoginSignup
2
6

More than 3 years have passed since last update.

【覚書】Nginxで複数のCORSとpreflightに対応する

Last updated at Posted at 2019-12-03

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;
}

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6