LoginSignup
21
19

More than 5 years have passed since last update.

nginxでレスポンスヘッダを書き換える

Posted at

upstreamからのレスポンスヘッダ(Content-Type)を書き換える必要があった1ので、対処しました。標準でできるかと思いきや、できないようで、headers-more-nginx-moduleを追加で入れることで解決しました。OpenRestyにバンドルされているモジュールで、nginxでもビルドオプションを追加して利用することができます。

静的ファイルでも検証ができるので、Welcome to nginx!ページのContent-Typeを変えてみます。

add_header

標準だとadd_headerがあるんですが、これはそのまま追加するので、すでにあるヘッダは二重につくことになります。2

Content-Typeに関しては、複数値ではダメ(そう)で、解釈はクライアントの実装に依存し、必ずしも期待する動きをしないので、ちゃんと置き換える必要があります。

nginx.conf(抜粋)
 location / {
    add_header 'Content-Type' 'application/json';
    root   html;
    index  index.html index.htm;
}

curlで確認

curl --dump-header - localhost

HTTP/1.1 200 OK
Server: nginx/1.11.8
Date: Tue, 17 Jan 2017 17:35:45 GMT
Content-Type: text/html     <— 1個目のContent-Type
Content-Length: 612
Last-Modified: Tue, 17 Jan 2017 14:48:14 GMT
Connection: keep-alive
ETag: "587e2eae-264"
Content-Type: application/json      <— 2個目のContent-Type
Accept-Ranges: bytes

bodyの内容…

2個目のContent-Typeが出現しました。

headers-more-nginx-module

今度は、headers-more-nginx-moduleのmore_set_headersを使って書き換えます。

nginx.conf(抜粋)
 location / {
    # htmlだけど、application/jsonで返す
    more_set_headers 'Content-Type: application/json';
    root   html;
    index  index.html index.htm;
}

curlで確認

curl --dump-header - localhost

HTTP/1.1 200 OK
Server: nginx/1.11.8
Date: Tue, 17 Jan 2017 17:42:27 GMT
Content-Type: application/json       <— Content-Typeがjson一のみ。
Content-Length: 612
Last-Modified: Tue, 17 Jan 2017 14:48:14 GMT
Connection: keep-alive
ETag: "587e2eae-264"
Accept-Ranges: bytes

bodyの内容…

ちゃんと書き換わっています。

他にも、レスポンスステータスや、Content-Typeを条件にして、それにマッチした時だけ追加/書き換えるといったことができます。他の使い方は、headers-more-nginx-moduleのgithubに例が載っています。


  1. JSONを返しているのに、text/htmlと言い張る奴。そして奴自身には手を出せない。 

  2. RFC的には、値が複数持てるものに関してはOKらしく、許可されたヘッダだと、複数の同名ヘッダはカンマ区切りの複数の値と同じ意味となり、順序もそのヘッダの順番が値の順番となるべきである。 

21
19
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
21
19