Nginx+Lua+Redis 對請求進行限制html
1、概述nginx
需求:全部訪問/myapi/**的請求必須是POST請求,並且根據請求參數過濾不符合規則的非法請求(黑名單), 這些請求一概不轉發到後端服務器(Tomcat)redis
實現思路:經過在Nginx上進行訪問限制,經過Lua來靈活實現業務需求,而Redis用於存儲黑名單列表。後端
相關nginx上lua或redis的使用方式能夠參考我以前寫的一篇文章:api
2、具體實現服務器
1.lua代碼curl
本例中限制規則包括(post請求,ip地址黑名單,請求參數中imsi,tel值和黑名單)post
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.confui
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;
}lua
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"