1. Background
In our daily maintenance of the website, we often encounter such a requirement. In order to block certain crawlers or malicious users from making requests to the server, we need to establish a Dynamic IP blacklist. For IPs in the blacklist, services will be denied.
2. Architecture
There are many ways to implement the IP blacklist function:
1. At the operating system level, Configure iptables to reject network requests for specified IPs;
2. At the web server level, configure the IP blacklist through nginx's own deny option or the lua plug-in;
3. At the application level, at Before requesting service, check whether the client IP is in the blacklist.
In order to facilitate management and sharing, we implement the IP blacklist function through the nginx lua redis architecture. The architecture diagram is as follows:
##Architecture diagram
3. Implementation
1. Install the nginx lua module. It is recommended to use openresty, which is an nginx server that integrates various lua modules:openresty
nginx Configuration
The nginx process allocates a 1m shared memory space to cache ip blacklist For the list, see: https://github.com/openresty/lua-nginx-module#lua_shared_dictaccess_by_lua_file lua/ip_blacklist.lua;
Specify the location of the lua script4. Configure the lua script and regularly obtain the latest IP blacklist from redis. For the file content, see:
https://gist.github.com/ceelog/ 39862d297d9c85e743b3b5111b7d44cb
##lua script content5. Create a new set type data ip_blacklist on the redis server and add the latest ip blacklist.
After completing the above steps, reload nginx and the configuration will start to take effect
access denied
The above is the detailed content of How Nginx uses Lua+Redis to dynamically ban IPs. For more information, please follow other related articles on the PHP Chinese website!