7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NginxのリバプロでCORSとサヨナラする

Last updated at Posted at 2019-12-26

はじめに

いなたつアドカレの二十六(ry

はい、アドカレロスなので勝手に26日目書きます。

docker-composeを用いてフロントエンドとバックエンドを分離して開発するなんて場合は最近多々あるのではないでしょうか?
CORSに悩まされますよね。つらい。解決しましょう。

リバプロってなんだ?

リバースプロキシの略称ですね。
HTTPからアプリケーションサーバにリクエストを飛ばしたりするやつです。

Nginxの設定

default.conf
server {
    listen 80;
    root /usr/share/nginx/html;
    error_page 500 502 503 504 /error.html;
    location /error.html {
        internal;
    }

    location /api/ {
        proxy_pass http://[CONTANER_NAME]:8000;
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    
}

このように設定ファイルを書くことで/api/へのリクエストを任意の場所へアクセスを飛ばすことができます。
ここで、任意のCONTAINER_NAMEで任意のポート番号backend:8000みたいな感じバックエンドへと飛ばします。

/api/以外から始まるものは普段通り root /usr/share/nginx/html を参照してファイルを返却してくれ、かつ/api/のアクセスはapiにアクセスするといった感じです。

nginxでファイルを返したい時も、リバースプロキシでapiを叩きたい場合もhoge.com/hoge or hoge.com/api/hogeを叩くかで振り分けているため、オリジンが同一になるため、CORSにかかりません。

これで、あなたもCORSとはぐっばいです。

7
5
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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?