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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Solution to 0x80242008 error when installing Windows 11 10.0.22000.100 Solution to 0x80242008 error when installing Windows 11 10.0.22000.100 May 08, 2024 pm 03:50 PM

1. Start the [Start] menu, enter [cmd], right-click [Command Prompt], and select Run as [Administrator]. 2. Enter the following commands in sequence (copy and paste carefully): SCconfigwuauservstart=auto, press Enter SCconfigbitsstart=auto, press Enter SCconfigcryptsvcstart=auto, press Enter SCconfigtrustedinstallerstart=auto, press Enter SCconfigwuauservtype=share, press Enter netstopwuauserv , press enter netstopcryptS

Caching mechanism and application practice in PHP development Caching mechanism and application practice in PHP development May 09, 2024 pm 01:30 PM

In PHP development, the caching mechanism improves performance by temporarily storing frequently accessed data in memory or disk, thereby reducing the number of database accesses. Cache types mainly include memory, file and database cache. Caching can be implemented in PHP using built-in functions or third-party libraries, such as cache_get() and Memcache. Common practical applications include caching database query results to optimize query performance and caching page output to speed up rendering. The caching mechanism effectively improves website response speed, enhances user experience and reduces server load.

How to upgrade Win11 English 21996 to Simplified Chinese 22000_How to upgrade Win11 English 21996 to Simplified Chinese 22000 How to upgrade Win11 English 21996 to Simplified Chinese 22000_How to upgrade Win11 English 21996 to Simplified Chinese 22000 May 08, 2024 pm 05:10 PM

First you need to set the system language to Simplified Chinese display and restart. Of course, if you have changed the display language to Simplified Chinese before, you can just skip this step. Next, start operating the registry, regedit.exe, directly navigate to HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlNlsLanguage in the left navigation bar or the upper address bar, and then modify the InstallLanguage key value and Default key value to 0804 (if you want to change it to English en-us, you need First set the system display language to en-us, restart the system and then change everything to 0409) You must restart the system at this point.

How to find the update file downloaded by Win11_Share the location of the update file downloaded by Win11 How to find the update file downloaded by Win11_Share the location of the update file downloaded by Win11 May 08, 2024 am 10:34 AM

1. First, double-click the [This PC] icon on the desktop to open it. 2. Then double-click the left mouse button to enter [C drive]. System files will generally be automatically stored in C drive. 3. Then find the [windows] folder in the C drive and double-click to enter. 4. After entering the [windows] folder, find the [SoftwareDistribution] folder. 5. After entering, find the [download] folder, which contains all win11 download and update files. 6. If we want to delete these files, just delete them directly in this folder.

Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Apr 01, 2025 pm 03:06 PM

Causes and solutions for errors when using PECL to install extensions in Docker environment When using Docker environment, we often encounter some headaches...

WordPress site file access is restricted: Why is my .txt file not accessible through domain name? WordPress site file access is restricted: Why is my .txt file not accessible through domain name? Apr 01, 2025 pm 03:00 PM

Wordpress site file access is restricted: troubleshooting the reason why .txt file cannot be accessed recently. Some users encountered a problem when configuring the mini program business domain name: �...

Which country is the Nexo exchange from? Where is it? A comprehensive introduction to the Nexo exchange Which country is the Nexo exchange from? Where is it? A comprehensive introduction to the Nexo exchange Mar 05, 2025 pm 05:09 PM

Nexo Exchange: Swiss cryptocurrency lending platform In-depth analysis Nexo is a platform that provides cryptocurrency lending services, supporting the mortgage and lending of more than 40 crypto assets, fiat currencies and stablecoins. It dominates the European and American markets and is committed to improving the efficiency, security and compliance of the platform. Many investors want to know where the Nexo exchange is registered, and the answer is: Switzerland. Nexo was founded in 2018 by Swiss fintech company Credissimo. Nexo Exchange Geographical Location and Regulation: Nexo is headquartered in Zug, Switzerland, a well-known cryptocurrency-friendly region. The platform actively cooperates with the supervision of various governments and has been in the US Financial Crime Law Enforcement Network (FinCEN) and Canadian Finance

Compilation and installation of Redis on Apple M1 chip Mac failed. How to troubleshoot PHP7.3 compilation errors? Compilation and installation of Redis on Apple M1 chip Mac failed. How to troubleshoot PHP7.3 compilation errors? Mar 31, 2025 pm 11:39 PM

Problems and solutions encountered when compiling and installing Redis on Apple M1 chip Mac, many users may...

See all articles