How to use lua for nginx redis access control
1. Requirements analysis
\1. There are many ways for Nginx to handle access control, and there are also many implementation effects. Access IP segments, Access content restrictions, access frequency restrictions, etc.
\2. Using Nginx Lua Redis for access restriction mainly takes into account the need for fast access control in high concurrency environments.
\3. The process of Nginx processing requests is divided into 11 stages, which are:
post-read、server-rewrite、find-config、rewrite、post-rewrite、 preaccess、access、post-access、try-files、content、log.
In openresty, you can find:
set_by_lua,access_by_lua,content_by_lua,rewrite_by_lua等方法。
Then the access control should be , access stage.
Solution
According to normal logical thinking, the access control solution we would think of is as follows:
1. Detect whether it is forbidden? =》Yes, whether forbidden has expired: Yes, clear the record, return 200, normal access; No, return 403; =》No, return 200, normal access
2. Each visit, visit the user's visit Frequency 1 processing
3. Check whether the access frequency exceeds the limit. If it exceeds the limit, add a forbidden record and return 403
This is a simple solution. You can also add branches and leaves, and the access prohibition time is passed The algorithm is imported, and each time the concave curve increases.
Implementation method
First add the vhost configuration file for nginx. The vhost.conf part is as follows:
lua_package_path "/usr/local/openresty/lualib/?.lua;;";#告诉openresty库地址lua_package_cpath "/usr/local/openresty/lualib/?.so;;"; error_log /usr/local/openresty/nginx/logs/openresty.debug.log debug; server { listen 8080 default; server_name www.ttlsa.com; root /www/openresty; location /login { default_type 'text/html'; access_by_lua_file "/usr/local/openresty/nginx/lua/access_by_redis.lua";#通过lua来处理访问控制 } }
Access_by_redis.lua
After referring to the implementation of v2ex.com, we found that using a simple string storage solution is enough, so we chose redis as the storage method. The keys are:
User login record: user:127.0.0.1:time (unix timestamp)
Access restrictions: block:127.0.0.1
Connect to Redis first :
local red = redis:new()function M:redis() red:set_timeout(1000)local ok, err = red:connect("127.0.0.1", 6379)if not ok then ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) end end
According to our logical plan, the second step is to detect whether it is forbidden. Next, we will detect block:127.0.0.1. If the data is searched, check whether the time has expired. If it has not expired, 403 will be returned. Otherwise, directly Return 200:
function M:check1()local time=os.time() --system timelocal res, err = red:get("block:"..ngx.var.remote_addr)if not res then -- redis error ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) --redis get data error endif type(res) == "string" then --if red not null then type(red)==string if tonumber(res) >= tonumber(time) then --check if forbidden expired ngx.exit(ngx.HTTP_FORBIDDEN) --ngx.say("forbidden") end end }
The next step will be to check whether the access frequency is too high. If it is too high, it will be blacklisted.
The implementation method is to detect user:127.0.0.1 Whether the value of :time exceeds the standard:
function M:check2()local time=os.time() --system timelocal res, err = red:get("user:"..ngx.var.remote_addr..":"..time)if not res then -- redis error ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) --redis get data error endif type(res) == "string" then if tonumber(res) >= 10 then -- attack, 10 times request/s red:del("block:"..self.ip) red:set("block:"..self.ip, tonumber(time)+5*60 ) --set block time ngx.exit(ngx.HTTP_FORBIDDEN) end end end
Finally, remember to make an auto-increment in the time of each access, user:127.0.0.1:time:
function M:add()local time=os.time() --system time ok, err = red:incr("user:"..ngx.var.remote_addr..":"..time)if not ok then ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) --redis get data error end end
Then, test, I swiped the browser several times and found that after a while, 403 was returned. OK, done.
The above is the detailed content of How to use lua for nginx redis access control. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

Docker container startup steps: Pull the container image: Run "docker pull [mirror name]". Create a container: Use "docker create [options] [mirror name] [commands and parameters]". Start the container: Execute "docker start [Container name or ID]". Check container status: Verify that the container is running with "docker ps".

How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

Create a container in Docker: 1. Pull the image: docker pull [mirror name] 2. Create a container: docker run [Options] [mirror name] [Command] 3. Start the container: docker start [Container name]

Question: How to start Nginx? Answer: Install Nginx Startup Nginx Verification Nginx Is Nginx Started Explore other startup options Automatically start Nginx

Enable Redis slow query logs on CentOS system to improve performance diagnostic efficiency. The following steps will guide you through the configuration: Step 1: Locate and edit the Redis configuration file First, find the Redis configuration file, usually located in /etc/redis/redis.conf. Open the configuration file with the following command: sudovi/etc/redis/redis.conf Step 2: Adjust the slow query log parameters in the configuration file, find and modify the following parameters: #slow query threshold (ms)slowlog-log-slower-than10000#Maximum number of entries for slow query log slowlog-max-len
