LoginSignup
1
0

More than 1 year has passed since last update.

nginxのクロスドメイン設定

Last updated at Posted at 2021-09-14

やりたかったこと。

APIをPHPで作成する事になったため、nginxの設定でクロスドメインに対応させたかった。

本番環境はクロスドメイン通信を行わないが、開発環境では、

のようにドメインが異なったため、開発環境のみにクロスドメイン設定を入れたかった。

結果。

nginxの設定ファイルにて、クロスドメイン設定を定義。

nginx
  location ~ \.php$ {
    if ($request_method = 'OPTIONS') {
      add_header Access-Control-Allow-Methods 'POST, GET, OPTIONS';
      add_header Access-Control-Allow-Headers 'Origin, Authorization, X-Requested-With, Content-Type, Accept';
      add_header Access-Control-Allow-Origin 'http://localhost:3000';
      add_header Access-Control-Allow-Credentials 'true' always;
      add_header Access-Control-Max-Age 86400;
      add_header Content-Length 0;

      return 204;
    }

    add_header Access-Control-Allow-Origin 'http://localhost:3000';
    add_header Access-Control-Allow-Credentials 'true';

    #以降に通常の設定を定義

Access-Control-Allow-Credentials は、always を付与しておく必要があった。
# OPTIONS以外の「レスポンス:200」の場合でも必要でした。
# ちょっと時間が無く、詳しくは調べてません。。。

'OPTIONS' によるif文は、API通信で行われるPreflightリクエストの場合です。

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