4573

nginx+lua动态修改upstream实现动态代理

乐果   发表于   2017 年 09 月 30 日 标签:nginxlua

家里有台迷你主机作为家庭服务器,但是在公司或者其他地方想实时访问,以前常有的解决办法是用域名动态dns解析即 “花生壳” 来实现的,但问题是当家里的宽带ip发生变化时,“花生壳”虽然已经更新了dns的解析,但由于下游dns服务缓存的影响,生效会延迟,这样就存在临界时间段无法访问的问题。

最近,学习nginx+lua实现动态代理,即在外网服务器上搭一个代理,当家里ip发生改变时通知外网的代理服务;用户访问外网代理服务,间接访问家庭服务器时,已经知道ip发生变化了,这样即实现了无缝隙间断的访问~

nginx配置案例如下:

lua_shared_dict _ups_zone 64m;

server {
        listen       80;
        server_name  test.cn;
        access_log  off;

        location = /ups_update {
                default_type text/plain;
                content_by_lua '
                        local ups = ngx.req.get_uri_args()["ups"]
                        if ups == nil then
                                ngx.say("usage: /ups_update?ups=x.x.x.x")
                                return
                        end
                        local host = ngx.var.http_host
                        local ups_from = ngx.shared._ups_zone:get(host);
                        --ngx.log(ngx.WARN, host, " update upstream from ", ups_from, " to ", ups)
                        ngx.shared._ups_zone:set(host, ups);
                        ngx.say(host, " update upstream from ", ups_from, " to ", ups)
                ';
        }

        location / {
                set_by_lua $cur_ups '
                        local ups = ngx.shared._ups_zone:get(ngx.var.http_host)
                        if ups ~= nil then
                                --ngx.log(ngx.ERR, "get [", ups, "] from ngx.shared._ups_zone")
                                return ups
                        end
                '
                proxy_next_upstream off;
                proxy_set_header    Host $host;
                proxy_http_version  1.1;
                proxy_set_header    Connection  "";
                proxy_pass $scheme://$cur_ups;
        }
}

乐果   发表于   2017 年 09 月 30 日 标签:nginxlua

0

文章评论