LoginSignup
5
3

More than 5 years have passed since last update.

NGINXのproxy_hostを動的に指定する(リバースプロキシ)

Last updated at Posted at 2016-12-11

動的にproxy_hostを変える

NGINXのLua拡張を用いると色々と変数を用いて書き換えたり出来て、自由度が更に高くなります。
今回は動的に向き先を変えてほしいという依頼がきたので試してみましょう。

用意から行なう場合にはこちらも

CentOS7のNginxのLua拡張の用意の方法であればこちらが大変参考になります。
http://marmotte.pyrites.jp/blog/2015/10/17/build-for-nginx-plus-lua/

(yum installで入手できるnginxはLua拡張されていないのでrewrite_by_luaなどが使えません。)

試してみる

今回私が試したのは、

  • サブドメインがなければ、サブドメインを付けないでホストを指定
  • サブドメインがあったら、指定されているサブドメイン付きでホストを指定

という動きを期待したリバースプロキシ。
(※環境はDocker上のCentOS 7)

例:

というわけで書いたconfはこんな感じ。

nginx.conf

http {

    # ~~ 中略 ~~~

    # /etc/resolv.confにかいてあるnameserverIP
    resolver 10.0.2.3 valid=2s;

    server {
        listen       80;
        server_name  .new.com;

        # proxy_set_header    Host               'old.com'; # old.comで固定したい場合
        proxy_set_header    X-Real-IP          $remote_addr;
        proxy_set_header    X-Forwarded-Host   $host;
        proxy_set_header    X-Forwarded-Server $host;
        proxy_set_header    X-Forwarded-For    $proxy_add_x_forwarded_for;

        location / {
            set $upstream "";

            # Dynamic rewrite for proxy_pass
            rewrite_by_lua '
                ngx.var.upstream = "old.com";

                domain_table = {}
                for i in string.gmatch(ngx.var.host, "([^.]+)") do
                    table.insert(domain_table, i)
                end

                if table.getn(domain_table) == 3 then
                    ngx.var.upstream = domain_table[1] .. "." .. ngx.var.upstream
                end
            ';

            proxy_pass http://$upstream;
        }
    }
}

※4つ目のドメインは知らない漢(おとこ)の設定

rewrite_by_lua内でLuaの記述を行い、変数を書き換えています。
但し、resolverでそのサーバーのDNSを指定しないと動かないです。
(と、ここのコメントにそんな感じのことが書いてある気がする。
http://stackoverflow.com/questions/26956979/error-with-ip-and-nginx-as-reverse-proxy#comment42490335_26957754 )

そして、upstream変数をこんな風に書き換えてしまっても良かったのかしらというところが個人的にもやもやしてたりします。m(_ _)m

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