需求細(xì)節(jié):
一個web服務(wù),分為正式服務(wù)器和測試服務(wù)器,通過nginx代理,用戶首先訪問時會提交登錄請求(post方式)到nginx上,通過nginx判斷登錄用戶是否為測試用戶,若為測試用戶則轉(zhuǎn)發(fā)測試服務(wù)器。
碰到的問題:
1.判斷用戶已經(jīng)實現(xiàn)了,怎么實現(xiàn)后續(xù)請求都發(fā)到同一服務(wù)器?想通過保存一個變量來實現(xiàn),但是nginx變量是不能跨請求存在的,能否通過文件讀寫來保存變量?。
2.跳轉(zhuǎn)方式如何實現(xiàn)?
下面是我的部分代碼
首先訪問 127.0.0.1/smdb
location /smdb {
default_type 'text/plain';
set $jump 0;
access_log /var/log/nginx/smdb_access.log smdb;
error_log /var/log/nginx/error.log;
log_subrequest on;
lua_need_request_body on;
client_max_body_size 50k;
client_body_buffer_size 50k;
content_by_lua '
ngx.req.read_body()
local args, err = ngx.req.get_post_args()
if not args then
ngx.say("failed to get post args: ", err)
return
end
for key, val in pairs(args) do
if val == "test" then
ngx.var.jump = "1"
end
end
ngx.exec("/tosmdb")
';
}
location /tosmdb {
default_type 'text/plain';
echo $jump;#注釋掉下面,這里顯示為1即判斷出了用戶
if ($jump = "1"){
proxy_pass http://smdbtest;
}
if ($jump = "0"){
proxy_pass http://smdb;
}
}
你需要把用戶登錄后的憑證都放到 cookie 里面,然后就方便做驗算了。
詳見 https://github.com/cloudflare/lua-resty-cookie 里面的例子。
跳轉(zhuǎn)的方式用 proxy_pass
應(yīng)該沒問題,挺好的。