location中使用rewrite_by_lua導入lua腳本後,if條件語句失效

1.問題描述:

就是在我的上一篇文章中,研究如何“使用nginx + lua腳本 + redis進行token鑑權”時,遇到一個大坑。nginx的location中使用rewrite_by_lua來導入lua腳本後,if條件語句失效了,到那時嘗試了很多方法。最開始以爲自己寫錯變量,符號寫錯,還爲此刪除Openresty重新安裝了一遍,結果發現還是一樣。在location中定義的變量,經過lua腳本修改後,if語句失效了。

2.遇坑時的代碼

 #匹配下載請求前綴, 進行token鑑權
location ~ /download/files/.*?/data {
    set $backend '';
    default_type 'text/html';
    rewrite_by_lua_file  lua-resty-redis/lib/resty/token.lua;
    #echo 可以打印變量$backend出來
    echo $backend;
    if ( $backend = "download"){
       proxy_pass  http://download;
       break;
    }
    if ( $backend  =  "failure"){
       rewrite  ^/  /return.html;
   }
 }
local var = ngx.var
local arg = ngx.req.get_uri_args()
local cjson = require("cjson")
--在table的agr中獲取token, token字符串組合成的key值
if arg ~= nil and arg.token ~= nil and arg.token ~= '' then
  token = "download:files:" .. arg.token 
end

--連接redis
local redis = require "resty.redis"
local red = redis:new()

red:set_timeout(1000) -- 1 sec

local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
    ngx.say("failed to connect: ", err, "<br/>")
    return
end

-- 請注意這裏 auth 的調用過程 這是redis設置密碼的
local count
count, err = red:get_reused_times()
if 0 == count then
    ok, err = red:auth(password)
    if not ok then
         ngx.say(cjson.encode({code = 500,message = err}))
        return
    end
elseif err then
    	ngx.say("failed to get reused times: ", err, "<br/>")
    return
end

--redis中若 key 存在返回 1 ,否則返回 0 。
local res, errs = red:exists(token)

if res == 0 then
	ngx.var.backend = "failure"
else
    ngx.var.backend = "download"
end    

3.發現

用這個看起來貌似有點低級的問題問老大,老大因爲還要忙其他的事情,也表示很懵逼。叫我稍後把代碼發給他,晚上他有時間後再研究。後面我自己網上查找資料(也怪自己剛接觸lua + nginx, 不怎麼熟悉),最後發現:nginx中的if會在rewrite_by_lua之前運行,然而echo爲什麼在rewrite_by_lua之後運行,並且輸出被lua改變的變量值,這個暫時還不瞭解。

4.解決

所以知道問題的原因之後,原來的思路改變了一下,不需要在token.lua中驗證token並賦值給$backend變量然後返回。只是,在驗證token在redis中不存在時,跳轉到指定的頁面,後續的nginx代碼將被截斷,不再執行。如果token存在,則不進行任何處理,這樣,當執行完token.lua文件後,自動繼續nginx的代理服務。

本文重點是location中if條件語句失效遇到rewrite_by_lua會失效的問題。遇坑後修改的代碼可以查看我寫的另一篇文章–使用nginx + lua腳本 + redis進行token鑑權,這裏就不粘出代碼了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章