nginxで動的リバースプロキシ!
リバースプロキシで、ユーザによって遷移先を変更することを考える必要があり、
調査してみたらサクッとできたので備忘がてら投稿します
動的リバースプロキシというジャンルになるようです
今回はユーザのIPアドレス単位で遷移先を決定していますが、
nginxを使っているので、cookieの値をもとにredisからデータを取得することも可能です
なお、今回の実装においては、nginx+Lua+redisという構成で動作確認を実施しています
使用したソフトウェア
- ngx_openresty-1.9.7.2.tar.gz
nginxのCore機能とLuaをセットでパッケージ化したもの
公式サイト:https://openresty.org/en/ - redis
- httpd
動作イメージ
今回は、ユーザのIPアドレスに対して挙動が変わるように実装しています
- 全てのユーザからのアクセスに対して、redisを参照する処理を実行
- redis参照処理では、ユーザのIPアドレス(key)に対するvalueをredisから取得
- valueに個別ディレクトリがセットされている場合は、proxy_passに設定
設定(抜粋)
location / { set $upstream ""; rewrite_by_lua ' local res = ngx.location.capture("/redis") if res.status == ngx.HTTP_OK then ngx.var.upstream = res.body end '; proxy_pass http://127.0.0.1:81/$upstream/$1; } location /redis { internal; set $redis_key $remote_addr; redis_pass 127.0.0.1:6379; default_type text/html; }
実行結果
対象のデータにディレクトリがセットされていないケース
[root@hornet logs]# redis-cli 127.0.0.1:6379> get 192.168.0.101 "" 127.0.0.1:6379> quit [root@hornet logs]# curl http://192.168.0.101/index.html nginx-lua-test
key:192.168.0.101に対してvalueが設定されていないので、
/var/www/html/index.htmlを読みだしています
対象のIPアドレスにディレクトリがセットされているケース
[root@hornet logs]# redis-cli 127.0.0.1:6379> set 192.168.0.101 "test" OK 127.0.0.1:6379> get 192.168.0.101 "test" 127.0.0.1:6379> quit [root@hornet logs]# curl http://192.168.0.101/index.html nginx-lua-test@test directory
key:192.168.0.101に対してvalue:testが設定されているので、
/var/www/html/test/index.htmlを読みだしています
各index.htmlの内容
[root@hornet logs]# cat /var/www/html/index.html nginx-lua-test [root@hornet logs]# cat /var/www/html/test/index.html nginx-lua-test@test directory
Luaは使いこなしていくと奥が深そうですね
もうちょっと遊んでみたいと思います