Table of Contents
1. Requirements analysis
Solution
Implementation method
Home Database Redis How to use lua for nginx redis access control

How to use lua for nginx redis access control

Jun 02, 2023 pm 04:31 PM
redis lua nginx

怎么使用lua进行nginx redis访问控制

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.
Copy after login

In openresty, you can find:

set_by_lua,access_by_lua,content_by_lua,rewrite_by_lua等方法。
Copy after login

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来处理访问控制   }
}
Copy after login

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
Copy after login

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
}
Copy after login

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
Copy after login

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
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

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)

How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

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).

How to start containers by docker How to start containers by docker Apr 15, 2025 pm 12:27 PM

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 check whether nginx is started How to check whether nginx is started Apr 14, 2025 pm 01:03 PM

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.

How to create containers for docker How to create containers for docker Apr 15, 2025 pm 12:18 PM

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]

How to start nginx How to start nginx Apr 14, 2025 pm 01:06 PM

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

How to configure slow query log in centos redis How to configure slow query log in centos redis Apr 14, 2025 pm 04:54 PM

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

How to install redis in centos7 How to install redis in centos7 Apr 14, 2025 pm 08:21 PM

See all articles