nginx+lua+redis做訪問鑒權


  圖片服務器不符合安全

  主要參考鏈接:

  • https://blog.csdn.net/qq_27156945/article/details/104019069
  • https://blog.csdn.net/liz9411/article/details/102934568?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param

一、安裝

  需要安裝的組件:LuaJIT-2.0.4ngx_devel_kitlua-nginx-module、lua-resty-redis-master。前3個令nginx支持lua,而且需要編譯nginx。第4個讓lua能訪問redis。

  1. LuaJIT需要下載、編譯、安裝,不贅述。需要關注的是直接make和install會安裝到/usr/local目錄
  2. 編譯nginx,不贅述。需要關注幾點:
    1. 執行./configure命令時,要指定路徑:--add-module=/usr/local/src/ngx_devel_kit-0.3.1 --add-module=/usr/local/src/lua-nginx-module-0.10.9rc7 ;以及with-ld-opt參數:--with-ld-opt='-Wl,-rpath,/usr/local/lib,-z,relro -Wl,-z,now -pie',其中粗體的用來指明luajit的庫位置。
    2. 如果是對現有nginx進行補丁,那就make后把nginx覆蓋過去。不要make install
    3. configure時如果不知道之前版本有哪里模塊,可以用nginx -V得到
  3. lua腳本位置:nginx的配置文件中在http小結中需要配置:lua_package_path "/etc/nginx/lua/lib/?.lua;;";這里的/etc/nginx/lua/lib/是手工創建,把幾個組件中的.lua文件都集中過來了

二、代碼

  nginx的配置文件,此處僅用了access模塊,其他content、head等可以根據實際情況使用

    location ^~ /group1/M01/ {

        default_type 'text/html';
        access_by_lua_file  /etc/nginx/lua/lib/access.lua;

        proxy_pass http://filesvr;
        proxy_redirect default;
        port_in_redirect off;
    }

  lua腳本,此處僅連接redis,檢查是否存在該token,未做進一步權限鑒別。

local function close_redis(red)
    if not red then
        return
    end
    local ok,err = red:close();
    if not ok then
        ngx.say("close redis error : ",err);
    end
end


local redis = require("redis");

local red = redis:new();
red:set_timeout(1000)

local ip = "redis srv ip"
local port = 6379

local ok,err = red:connect(ip,port)
if not ok then
  --500
  ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end

local res, err = red:auth("passwd")
if not res then
  --500
  ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end

local ok, err = red:select(3)
if not ok then
  --500
  ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end

local token = ngx.var.arg_token
if token ~= nil and token ~= "" then
  local res, errs = red:exists(token)
  close_redis(red)
  if res == nil then
    --500
    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
  end
  if res==0 then
    --401
    ngx.exit(ngx.HTTP_UNAUTHORIZED)
  else
    return
  end
else
  --403
  ngx.exit(ngx.HTTP_FORBIDDEN)
end

 

三、坑

  僅記錄耗時間最久的幾個:

  • 運行時報找不到"resty.core",原因是高版本luajit強制使用resty.core,即使使用lua_load_resty_core off;也無法跳過。我是使用lua-nginx-module.v0.10.9rc7來解決。安裝resty應該也能解決。
  • lua腳本在require("redis");處報no file '/***/redis.lua。其實不是找不到該文件,而是文件屬性沒加x。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM