yum install -y epel-release
yum update
yum search openresty # 查看是否有可用包
yum install -y openresty啟動systemctl start openresty驗證服務狀態systemctl status openresty設置開機自啟systemctl enable openrestysystemctl stop openresty # 停止服務
systemctl restart openresty # 重啟服務
systemctl reload openresty # 重載配置(無需重啟服務)
使用
nginx配置文件
location / {root html;index index.html index.htm;//直接使用//content_by_lua_block {// ngx.say("Hello, OpenResty!")// ngx.var.uri獲得請求地址// ngx.say("Request URI: ", ngx.var.uri)// }//lua文件content_by_lua_file "/usr/local/openresty/nginx/conf/lua/app.lua";
}
app.lua
-- 獲取請求參數
local args = ngx.req.get_uri_args()
-- 設置響應頭
ngx.header.content_type = "application/json; charset=utf-8"ngx.say('{"code":2006,"data":[],"message":"請求成功"}')
使用解密
安裝
yum install openresty-opm
安裝
opm get SkyLothar/lua-resty-jwt引入
local jwt = require("resty.jwt")
使用
local secret = "wbrj" -- JWT簽名密鑰
local jwt_obj = jwt:verify(secret, headers["token"])
完整案例app.lua文件
-- 獲取請求參數
local args = ngx.req.get_uri_args()
-- 設置響應頭
ngx.header.content_type = "application/json; charset=utf-8"-- 引入JSON編碼庫
local cjson = require("cjson")local uri = ngx.var.uri-- 定義不需要攔截的路徑數組
local whitelist = {"/main/admin/login","/main/admin/wbUrl", --App綁定域名"/main/accset/select", --獲得套賬數"/main/accset/select", --獲得套賬數"/wbrjPys/accset/select",--獲得套賬數"/wbrjPys/static" -- 靜態文件
}
-- 檢查URI是否在白名單中
local in_whitelist = false
for _, path in ipairs(whitelist) doif string.find(uri, path) thenin_whitelist = truebreakend
end
-- 如果在白名單中,直接放行
if in_whitelist thenreturn
end-- 獲取所有請求頭信息
local headers = ngx.req.get_headers()-- 使用Lua表構建響應數據,code是2006
local response = {code = 2001,data = {},message = "簽權失敗",uri = headers['token']
}
local jwt = require("resty.jwt")-- 檢查請求頭中是否存在token字段
if headers["token"] and headers["token"] ~= "" then-- 使用示例local secret = "dade" -- JWT簽名密鑰local jwt_obj = jwt:verify(secret, headers["token"])response['valid'] = jwt_objngx.say(cjson.encode(response))
else--自動編碼為JSON字符串,自動處理轉義ngx.say(cjson.encode(response))
end