Original text: segmentfault.com/a/119000001…
In order to block some crawlers or malicious users’ requests to the server, we need to establish a dynamic IP blacklist. For IP addresses in the blacklist, services are denied.
There are many ways to implement the IP blacklist function:
1. At the operating system level, configure iptables to reject network requests from specified IP addresses.
2. At the Web Server level, configure IP blacklist through Nginx’s own deny option or lua plug-in;
3. At the application level, check whether the client IP address is on the blacklist before requesting service.
In order to facilitate management and sharing, we choose the architecture of Nginx+Lua+Redis to realize the function of IP blacklist. The architecture diagram is as follows:
1. Install the Nginx+Lua module
I recommend OpenResty, an Nginx server that integrates various Lua modules:
2. Install and start Redis server
Nginx configuration example:
Nginx configuration, where
lua_shared_dict ip_blacklist 1m
Copy the code
The Nginx process allocates a 1 MB shared memory space to cache the IP blacklist.
access_by_lua_file lua/ip_blacklist.lua;
Copy the code
Specify the lua script location.
4. Configure lua script to obtain the latest IP blacklist from Redis periodically.
5. Create data of the Set type ip_blacklist on the Redis server and add it to the latest IP blacklist.
After completing the above steps, reload nginx and the configuration takes effect. If your IP address is in the blacklist, access will be denied, as shown below:
Nginx+Lua+Redis IP blacklist function, has the following advantages:
1, simple configuration, light weight, almost no impact on server performance;
2. Multiple servers can share the blacklist through Redis instance;
3, dynamic configuration, you can manually or through some automatic way to set the blacklist in Redis.
Recent hot articles recommended:
1.1,000+ Java Interview Questions and Answers (2021)
2. Don’t use if/ else on full screen again, try strategy mode, it smells good!!
3. Oh, my gosh! What new syntax is xx ≠ null in Java?
4.Spring Boot 2.5 is a blockbuster release, and dark mode is exploding!
5. “Java Development Manual (Songshan version)” the latest release, quick download!
Feel good, don’t forget to click on + forward oh!