openresty开发系列34--openresty执行流程之4访问阶段
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.1、nginx.conf配置文件
location /lua_access {
? access_by_lua_file /usr/local/luajit/test_access.lua;
? echo "access";
}
?1.2、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來決定是否有訪問權限。
轉載于:https://www.cnblogs.com/reblue520/p/11446457.html
總結
以上是生活随笔為你收集整理的openresty开发系列34--openresty执行流程之4访问阶段的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: openresty开发系列33--ope
- 下一篇: openresty开发系列35--ope