LoginSignup
0
2

More than 5 years have passed since last update.

NginxでのCORS設定(Cookie利用版)

Posted at

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を使うということなので、そもそもサービスとしてどうなの?はありますが、やむを得ない場合は追加)

0
2
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
0
2