以下是一个基本的 Nginx Lua 脚本,用于检查访问源 IP 地址和请求是否在本地 Redis 中的 key 值中。如果存在,则返回 200 正常的 index.html 页面,否则返回 403 错误页面。

-- 引入 redis 模块
local redis = require 'resty.redis'

-- 创建 redis 连接
local red = redis:new()
red:set_timeout(1000) -- 1 秒

-- 连接 redis 服务器
local ok, err = red:connect('127.0.0.1', 6379)
if not ok then
    ngx.log(ngx.ERR, 'failed to connect to redis: ', err)
    ngx.exit(500)
end

-- 获取客户端 IP 地址
local client_ip = ngx.var.remote_addr

-- 获取请求 URL
local request_uri = ngx.var.request_uri

-- 构造 redis 中的 key 值
local redis_key = client_ip .. request_uri

-- 查找 redis 中是否存在该 key 值
local exists, err = red:exists(redis_key)
if not exists then
    ngx.log(ngx.ERR, 'redis key does not exist: ', redis_key)
    ngx.exit(403)
end

-- 关闭 redis 连接
local ok, err = red:close()
if not ok then
    ngx.log(ngx.ERR, 'failed to close redis connection: ', err)
end

-- 返回 200 正常的 index.html 页面
ngx.exit(ngx.HTTP_OK)

请注意,此脚本仅用于演示目的,并且可能需要进行修改才能适合您的具体情况。请根据您的需求进行适当的更改。

Nginx Lua 脚本:使用 Redis 验证 IP 和请求以阻止访问

原文地址: https://www.cveoy.top/t/topic/ner9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录