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

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

 

1、概述nginx

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

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

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

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

 

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 then10    myIP = ngx.req.get_headers()["x_forwarded_for"]11 end12 if myIP == nil then13    myIP = ngx.var.remote_addr14 end15         16 if ngx.re.match(ngx.var.uri,"^(/myapi/).*$") then17     local method = ngx.var.request_method18     if method == 'POST' then19         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 then25             --ngx.say("This is 'Black List' request")26             ngx.exit(ngx.HTTP_FORBIDDEN)27         end28     else29         --ngx.say("This is 'GET' request")30         ngx.exit(ngx.HTTP_FORBIDDEN)31     end32 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"

相關文章
相關標籤/搜索