Nginx+lua+redis restrictions on Requests
I. Overview
Requirements: All requests to access/myapi/** must be post requests, and illegal requests (blacklists) that are not compliant based on request parameters are not forwarded to back-end servers (TOMCAT)
Implementation of the idea: through the Nginx access restrictions, through the flexibility of LUA to achieve business needs, and Redis is used to store the blacklist list.
The use of Lua or Redis on the relevant nginx can be referred to an article I wrote earlier:
openresty (Nginx), LUA, drizzle research http://www.cnblogs.com/huligong1234/p/4007103.html
Second, the concrete realization
1.lua Code
In this example, the restriction rules include (POST request, IP address blacklist, Imsi,tel value and blacklist in Request parameter)
1 --access_by_lua_file '/usr/local/lua_test/my_access_limit.lua ';2 ngx.req.read_body ()3 4 LocalRedis =require "Resty.redis"5 LocalRed =redis.new ()6Red.connect (Red,'127.0.0.1','6379')7 8 LocalMyIP = Ngx.req.get_headers () ["X-real-ip"]9 ifMyIP = =Nil ThenTenMyIP = Ngx.req.get_headers () ["x_forwarded_for"] One End A ifMyIP = =Nil Then -MyIP =ngx.var.remote_addr - End the - ifNgx.re.match (Ngx.var.uri,"^ (/myapi/). *$") Then - LocalMETHOD =Ngx.var.request_method - ifmethod = ='POST' Then + Localargs =Ngx.req.get_post_args () - + LocalHasip = Red:sismember ('Black.ip', MyIP) A LocalHasimsi = Red:sismember ('Black.imsi', Args.imsi) at LocalHastel = Red:sismember ('Black.tel', Args.tel) - ifhasip==1 orhasimsi==1 orhastel==1 Then - --Ngx.say ("This is ' Black List ' request") - Ngx.exit (NGX. Http_forbidden) - End - Else in --Ngx.say ("This is ' GET ' request") - Ngx.exit (NGX. Http_forbidden) to End + 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. Add Blacklist rule data
#redis-cli sadd black.ip ' 153.34.118.50 '
#redis-cli sadd black.imsi ' 460123456789 '
#redis-cli sadd black.tel ' 15888888888 '
You can view the columns by Redis-cli Smembers Black.imsi to show that the thin
4. Verify the results
#curl-D "imsi=460123456789&tel=15800000000" "HTTP://WWW.MYSITE.COM/MYAPI/ABC"
Nginx+lua+redis restrictions on Requests