openresty開發系列34--openresty執行流程之4訪問階段
訪問階段
用途:訪問權限限制 返回403
nginx:allow 容許,deny 禁止
allow ip;
deny ip;
涉及到的網關,有不少的業務 都是在access階段處理的,有複雜的訪問權限控制
nginx:allow deny 功能太弱
一)access_by_lua
語法:access_by_lua <lua-script-str>
語境:http,server,location,location if
階段:access tail
爲每一個請求在訪問階段的調用lua腳本進行處理。主要用於訪問控制,能收集到大部分的變量。
用於在 access 請求處理階段插入用戶 Lua 代碼。這條指令運行於 access 階段的末尾,
所以老是在 allow 和 deny 這樣的指令以後運行,雖然它們同屬 access 階段。
location /foo {
access_by_lua_block {
ngx.log(ngx.DEBUG,"12121212");
}
allow 10.11.0.215;
echo "access";
}
access_by_lua 經過 Lua 代碼執行一系列更爲複雜的請求驗證操做,好比實時查詢數據庫或者其餘後端服務,
以驗證當前用戶的身份或權限。
利用 access_by_lua 來實現 ngx_access 模塊的 IP 地址過濾功能:
location /access {
access_by_lua_block {
if ngx.var.arg_a == "1" then
return
end
if ngx.var.remote_addr == "10.11.0.215" then
return
end
ngx.exit(403)
}
echo "access";
}
對於限制ip的訪問,等價於
location /hello {
allow 10.11.0.215;
deny all;
echo "hello world";
}
二)access_by_lua_file
1.一、nginx.conf配置文件
location /lua_access {
access_by_lua_file /usr/local/luajit/test_access.lua;
echo "access";
}
1.二、test_access.lua
if ngx.req.get_uri_args()["token"] ~= "123" then
return ngx.exit(403)
end
即若是訪問如http://10.11.0.215/lua_access?token=234將獲得403 Forbidden的響應。
這樣咱們能夠根據如cookie/用戶token來決定是否有訪問權限。nginx