Nginx+Lua+Redis 對請求進行限制


Nginx+Lua+Redis 對請求進行限制

 

一、概述

需求:所有訪問/myapi/**的請求必須是POST請求,而且根據請求參數過濾不符合規則的非法請求(黑名單), 這些請求一律不轉發到后端服務器(Tomcat)

實現思路:通過在Nginx上進行訪問限制,通過Lua來靈活實現業務需求,而Redis用於存儲黑名單列表。

相關nginx上lua或redis的使用方式可以參考我之前寫的一篇文章:

openresty(nginx)、lua、drizzle調研 http://www.cnblogs.com/huligong1234/p/4007103.html

 

二、具體實現

1.lua代碼

本例中限制規則包括(post請求,ip地址黑名單,請求參數中imsi,tel值和黑名單)

 1 -- access_by_lua_file '/usr/local/lua_test/my_access_limit.lua';
 2 ngx.req.read_body()
 3 
 4 local redis = require "resty.redis"
 5 local red = redis.new()
 6 red.connect(red, '127.0.0.1', '6379')
 7 
 8 local myIP = ngx.req.get_headers()["X-Real-IP"]
 9 if myIP == nil then
10    myIP = ngx.req.get_headers()["x_forwarded_for"]
11 end
12 if myIP == nil then
13    myIP = ngx.var.remote_addr
14 end
15         
16 if ngx.re.match(ngx.var.uri,"^(/myapi/).*$") then
17     local method = ngx.var.request_method
18     if method == 'POST' then
19         local args = ngx.req.get_post_args()
20         
21         local hasIP = red:sismember('black.ip',myIP)
22         local hasIMSI = red:sismember('black.imsi',args.imsi)
23         local hasTEL = red:sismember('black.tel',args.tel)
24         if hasIP==1 or hasIMSI==1 or hasTEL==1 then
25             --ngx.say("This is 'Black List' request")
26             ngx.exit(ngx.HTTP_FORBIDDEN)
27         end
28     else
29         --ngx.say("This is 'GET' request")
30         ngx.exit(ngx.HTTP_FORBIDDEN)
31     end
32 end

 

2.nginx.conf

location / {
root html;
index index.html index.htm;

access_by_lua_file /usr/local/lua_test/my_access_limit.lua;

proxy_pass http://127.0.0.1:8080;
client_max_body_size 1m;
}

 

3.添加黑名單規則數據

#redis-cli sadd black.ip '153.34.118.50'
#redis-cli sadd black.imsi '460123456789'
#redis-cli sadd black.tel '15888888888'

 

可以通過redis-cli smembers black.imsi 查看列表明細

 

4.驗證結果

#curl -d "imsi=460123456789&tel=15800000000" "http://www.mysite.com/myapi/abc"


免責聲明!

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



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