Nginx+lua+redis实现post请求接口黑名单

来自Linux78|wiki

概述

需求:所有访问/webapi/**的请求必须是POST请求,而且根据请求参数过滤不符合规则的非法请求(黑名单), 这些请求一律不转发到后端服务器(Tomcat) 实现思路:通过在Nginx上进行访问限制,通过Lua来灵活实现业务需求,而Redis用于存储黑名单列表。

具体实现

1.lua代码

本例中限制规则包括(post请求,ip地址黑名单,请求参数中imsi,tel值和黑名单)

cat /usr/local/nginx/conf/lua/ipblacklist.lua
ngx.req.read_body()

local redis = require "resty.redis"
local red = redis.new()
red.connect(red, '127.0.0.1', '6379')

local myIP = ngx.req.get_headers()["X-Real-IP"]
if myIP == nil then
  myIP = ngx.req.get_headers()["x_forwarded_for"]
end
if myIP == nil then
  myIP = ngx.var.remote_addr
end

if ngx.re.match(ngx.var.uri,"^(/webapi/).*$") then
   local method = ngx.var.request_method
   if method == 'POST' then
       local args = ngx.req.get_post_args()

       local hasIP = red:sismember('black.ip',myIP)
       local hasIMSI = red:sismember('black.imsi',args.imsi)
       local hasTEL = red:sismember('black.tel',args.tel)
       if hasIP==1 or hasIMSI==1 or hasTEL==1 then
           --ngx.say("This is 'Black List' request")
           ngx.exit(ngx.HTTP_FORBIDDEN)
         end
       else
           --ngx.say("This is 'POST' request")
           ngx.exit(ngx.HTTP_FORBIDDEN)
         end
        end

2.nginx.conf

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

access_by_lua_file /usr/local/nginx/conf/lua/ipblacklist.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.kjios.com/myapi/111"
 <html>
 <head><title>404 Not Found</title></head>
 <body bgcolor="white">
 <center><h1>404 Not Found</h1></center>
 <hr><center>nginx</center>
 </body>
 </html>