NginxでCORSの設定するときにとりあえず全オープンするために
Access-Control-Allow-Origin *
の設定がググるとよく出てくるのだけど、これだとCookieを利用している場合、 *が許可されないため、CORSがうまく動かない。
nginx.conf
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods "POST, GET, OPTIONS";
add_header Access-Control-Allow-Headers "Origin, Authorization, Accept";
add_header Access-Control-Allow-Credentials true;
以下のような設定にすると、基本は動くようになる。
(originヘッダ乗せてこないとうまく動作しないため、ない場合は動作しないけど、、)
↓
nginx.conf
if ($http_origin = ''){
set $http_origin "*";
}
add_header P3P "CP=\"UNI CUR OUR\"";
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Credentials true always;
add_header Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers "Origin, Authorization, Accept" always;
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers "Origin, Authorization, Accept" always;
add_header Access-Control-Allow-Credentials true always;
add_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}
補足:
P3P "CP=\"UNI CUR OUR\ はIEでiFrameかつクロスドメインでCookieを使いたい場合に追加
(サードパーティCookieを使うということなので、そもそもサービスとしてどうなの?はありますが、やむを得ない場合は追加)