LoginSignup
14
9

More than 5 years have passed since last update.

nginx でリバースプロキシする時、レスポンスがエラーでもヘッダー追加をさせる方法

Posted at

例えばRESTサーバー等を立てる時、その前にリバースプロキシ入れますよね?

で、RESTサーバーにいちいちヘッダー付けされるの面倒なので、
リバースプロキシで Access-Control-Allow-Origin とかのヘッダーをつけさせるとしましょう。

例えば、こんな感じになるでしょう。

nginx.conf
server {
        listen 80;
        listen [::]:80;
        server_name api.example.com;

        location / {

                if ($request_method = 'OPTIONS') {
                        add_header 'Access-Control-Allow-Credentials' 'true';
                        add_header 'Access-Control-Allow-Headers'     'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
                        add_header 'Access-Control-Allow-Methods'     'GET, DELETE, OPTIONS, POST, PUT';
                        add_header 'Access-Control-Allow-Origin'      'http://example.com';
                        add_header 'Access-Control-Max-Age'           2592000;
                        add_header 'Content-Length'                   0;
                        add_header 'Content-Type'                     'text/plain charset=UTF-8';
                        return 204;
                }

                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Origin'      'http://example.com';

                proxy_pass http://localhost:8080/;
        }

基本はこれで良いんですが、これだけだとちょっと困ったことがあって、
後ろのサーバーからのレスポンスが404とかのエラーだと、設定したヘッダーをつけて返してくれないんですよね。

ちなみに、 Fetch API だとこうなる

Fetch API cannot load http://api.example.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

例えば Fetch API で持ってこようとしてもこうなる。 アイエエエ!? エラー!? エラーナンデ!?

よって、Fetch API の方に no-cors モードを設定して、空のレスポンスを返却させることでエラーを回避する。
CORS、corosべし。慈悲は無い。(これが言いたくて記事書いた。)

…とはならない! 実際、エラーコードは必要。

レスポンスコードに関わらず、常にヘッダーを出力させる方法

答えは単純でした。

nginx.conf
add_header 'Access-Control-Allow-Origin'      'http://example.com' always;

のように、後ろに always をつける事で、レスポンスコードにかかわらずヘッダーをつけてくれるみたいです。

実は公式にきちんと書いてあるのですが、何も知らないと
「なんでヘッダーついてないの?」ってなって全然違うところ調べ始めたりするから要注意。

14
9
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
14
9