匿名
未登录
登录
Linux78|wiki
搜索
查看“Nginx+lua+redis实现post请求接口黑名单”的源代码
来自Linux78|wiki
名字空间
页面
讨论
更多
更多
页面选项
查看
查看源代码
历史
←
Nginx+lua+redis实现post请求接口黑名单
因为以下原因,您没有权限编辑本页:
您所请求的操作仅限于该用户组的用户使用:
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.验证结果 <nowiki>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></nowiki>
返回至
Nginx+lua+redis实现post请求接口黑名单
。
导航
导航
首页
最近更改
随机页面
栏目
Nginx
Kubernetes
Spring Cloud
Wiki工具
Wiki工具
特殊页面
页面工具
页面工具
用户页面工具
更多
链入页面
相关更改
页面信息
页面日志