LoginSignup
18
11

More than 5 years have passed since last update.

Nginxのproxy先にうまくHostヘッダーが渡らなかった事案と対応

Last updated at Posted at 2016-06-06

タイトルそのままなのですが、このような事案がありました。
単純に proxy_set_header つければ良い、
という話とはちょっと異なります。

upstreamディレクティブでproxyすると…

パフォーマンス改善のため1、proxy_passにエンドポイントをそのまま指定するのではなく
upstreamディレクティブを利用するように変更しました。
こんな感じ?

変更前

location / {
  proxy_pass http://oreore-microservice.com;
  proxy_set_header Host $proxy_host;
}

変更後

upstream hogehoge_server {
  keepalive 10;

  server oreore-microservice.com:80;
}

location / {
  proxy_pass http://hogehoge_server;
  proxy_set_header Host $proxy_host;
}

すると変更後、upstream先に渡るHostヘッダーが hogehoge_server になってしまったんですね。まいっちんぐ。


対応策

根本対応としては
「proxy_set_header に固定でproxy hostを設定する」
しかなさそうでした2
今回であれば、以下の様な感じでしょうか。

proxy_set_header Host oreore-microservice.com;

複数ホスト指定の場合

serverfaultにあったのですが、直接proxyするのではなくローカルに複数port立てちゃって
そのport毎にヘッダー設定する、というテクニックを使っていました。
なるほどー

server {
  listen      8001 default_server;
  server_name oreore-microservice-a;
  location / {
    proxy_pass       http://oreore-microservice-a.com;
    proxy_set_header Host oreore-microservice-a.com;
  }
}
server {
  listen      8002 default_server;
  server_name oreore-microservice-b;
  location / {
    proxy_pass       http://oreore-microservice-b.com;
    proxy_set_header Host oreore-microservice-b.com;
  }
}

upstream main {
  server 127.0.0.1:8001;
  server 127.0.0.1:8002;
}

server {
  listen      80;
  server_name example.com;
  location / {
    proxy_pass http://main;
  }
}

Luaで変えちゃう

実は今回、upstream先もupstream名もNginx+Luaで動的に生成していたので固定指定だとつらい感じでした。
しかし幸いにもLua側でもホスト取得することが可能だったので、今回はnginx変数に突っ込んで対応しました。

-- Lua側
-- 実際にはなんかロジックで入れてる
ngx.var.oreore_proxy_host = "oreore-microservice.com"


# Nginx側
proxy_set_header Host $oreore_proxy_host;


以上、ちょっとした罠に引っかかった、というお話でした。


  1. 例のkeepalive対応 

  2. 他の方法知ってる方がいれば教えて下さい〜 

18
11
2

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
18
11