Home  >  Article  >  Database  >  How Nginx uses Lua+Redis to dynamically ban IPs

How Nginx uses Lua+Redis to dynamically ban IPs

WBOY
WBOYforward
2023-05-26 10:50:541903browse

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:

How Nginx uses Lua+Redis to dynamically ban IPs

##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:

How Nginx uses Lua+Redis to dynamically ban IPsopenresty

2. Install and start the redis server;

3. Configure nginx Example:

How Nginx uses Lua+Redis to dynamically ban IPsnginx Configuration

#lua_shared_dict ip_blacklist 1m;

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_dict

access_by_lua_file lua/ip_blacklist.lua;

Specify the location of the lua script

4. 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 content

5. Create a new set type data ip_blacklist on the redis server and add the latest ip blacklist. How Nginx uses Lua+Redis to dynamically ban IPs
After completing the above steps, reload nginx and the configuration will start to take effect

At this time, access the server. If your IP address is in the blacklist, access denied:

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete