Hello!
2012/10/18 汪利福:
> 刚刚接触Nginx,想实现一个这样的功能:
> 1、反向代理,网站的真实IP由Lua + Redis从Redis里取得
> 2、Redis服务器里不仅存着HOST到IP的映射,还保存着一个配置开关test,从Redis里一次性取得,并通过这个值
> 来控制一个Nginx模块(注册到ACCESS阶段)里的test指令的开关
>
> 不知道我的配置错误在哪,test的开关测试是无效的,不管我在redis里怎么设置,远行结果来看永远是off的
>
> location = /redis {
> internal;
> set_unescape_uri $key $arg_key;
> redis2_query get $key;
> redis2_pass redis_backend;
> }
>
> location / {
> set $ip'';
> set $test_switch '';
> rewrite_by_lua '
> local key = ngx.var.http_host
> local res = ngx.location.capture(
> "/redis", { args = { key = key } }
> )
>
> local parser = require "redis.parser"
> local result, typ = parser.parse_reply(res.body)
> if typ ~= parser.BULK_REPLY or not result then
> ngx.exit(500)
> end
> #Redis里返回的内容类似于"ip=1.1.1.1 test=on“
> _, _, ngx.var.ip= string.find(result, "ip=([%d%.]*)")
> _, _, ngx.var.test_switch = string.find(result, "test=(%a+)")
> ';
>
> if ($test_switch ~* on) {
> test on;
> }
>
> proxy_pass $scheme://$ip$request_uri;
> }
>
这是因为 if 配置指令永远运行在 rewrite_by_lua 指令之前,即使你在配置文件中把 if 写在 rewrite_by_lua
的后面。所以 if 在读取 $test_switch 的值时,总是得到空串值,毕竟你的 Lua 代码尚未运行呢。
关于 nginx 配置指令的执行顺利的相关细节,请参考我的 Nginx 连载教程之“Nginx 配置指令的执行顺序”系列:
http://agentzh.org/misc/nginx/agentzh-nginx-tutorials-zhcn.html#02-NginxDirectiveExecOrder01
值得一提的是,推荐使用 lua-resty-redis 库来从 Lua 中直接访问 redis:
https://github.com/agentzh/lua-resty-redis
通过 Nginx 子请求访问 ngx_redis2 模块的开销一般都明显大于 lua-resty-redis 库。
另外,我把此邮件同时抄送给了 openresty
中文邮件列表:https://groups.google.com/group/openresty
(国内访问列表的首页可能需要翻墙),欢迎你加入这个列表并在那里和我们交流这样的问题 :) 谢谢合作!
Best regards,
-agentzh