🔥 热门模块(知名度 ★★★★★)
ngx_lua (OpenResty) 🥇 NO.1
OpenResty 是基于 Nginx 和 LuaJIT 的 Web 平台,核心是 ngx_lua 模块。 它允许在 Nginx 中直接编写 Lua 脚本,实现复杂的业务逻辑,无需重启服务器即可更新代码。 被 Cloudflare、GitHub 等大公司广泛使用。
📦 安装方式
推荐直接安装 OpenResty(已集成 ngx_lua):
# Ubuntu/Debian
wget -O - https://openresty.org/package/pubkey.gpg | sudo apt-key add -
sudo apt-add-repository -y "deb http://openresty.org/package/ubuntu $(lsb_release -sc) main"
sudo apt update
sudo apt install -y openresty
# 或使用 Docker
docker pull openresty/openresty
- 在 Nginx 中运行 Lua 脚本
- 极高的性能(LuaJIT 编译)
- 丰富的 API 和生态
- 热代码加载
- 协程支持
- 非阻塞 I/O
配置示例
location /hello { content_by_lua_block { ngx.say("Hello, Lua!") } } location /api { content_by_lua_block { local cjson = require("cjson") ngx.header.content_type = "application/json" ngx.say(cjson.encode({name = "OpenResty", version = "1.21"})) } }
njs (Nginx JavaScript) 🥈 NO.2
njs 是 Nginx 官方推出的 JavaScript 模块,允许在 Nginx 配置中使用 JavaScript 脚本。 与 ngx_lua 类似,但使用更流行的 JavaScript 语言,学习成本更低。
📦 安装方式
njs 已作为动态模块包含在官方 Nginx 包中:
# Ubuntu/Debian - 安装 njs 模块
sudo apt install -y libnginx-mod-http-js
# 配置文件中加载
load_module modules/ngx_http_js_module.so;
# 或使用 Docker(官方镜像已包含)
docker pull nginx
- Nginx 官方支持
- 使用 JavaScript 语言
- 轻量级脚本引擎
- 与 Nginx 深度集成
- 持续更新维护
配置示例
# 加载模块 load_module modules/ngx_http_js_module.so; http { js_path "/etc/nginx/js/"; js_import api from api.js; location /hello { js_content api.hello; } }
// api.js function hello(r) { r.return(200, "Hello, JavaScript!"); } export default { hello };
🛡️ 安全模块(知名度 ★★★★☆)
ModSecurity 🥉 NO.3
ModSecurity 是开源的 Web 应用防火墙(WAF),最初为 Apache 开发, 现在有 Nginx 版本。提供 SQL 注入、XSS、CSRF 等攻击防护,支持自定义规则。
📦 安装方式
# 需要编译安装,或使用预编译包
# Ubuntu/Debian
sudo apt install -y libmodsecurity3 modsecurity
# 编译安装(从源码)
git clone https://github.com/SpiderLabs/ModSecurity
cd ModSecurity
git submodule init && git submodule update
./build.sh
./configure --with-nginx
make
sudo make install
- OWASP 核心规则集
- SQL 注入防护
- XSS 攻击防护
- 请求/响应检查
- IP 信誉检查
- 详细日志记录
配置示例
http { modsecurity on; modsecurity_rules_file /etc/nginx/modsec/modsecurity.conf; location / { modsecurity_rules "SecRuleEngine On"; } }
ngx_brotli NO.4
ngx_brotli 是 Google Brotli 压缩算法的 Nginx 模块。 Brotli 压缩率比 gzip 高 20-26%,特别适合文本资源压缩, 可显著减少传输数据量,提升页面加载速度。
📦 安装方式
# 需要编译安装
git clone https://github.com/google/ngx_brotli
cd ngx_brotli
git submodule update --init
# 编译 Nginx 时添加模块
./configure --add-module=/path/to/ngx_brotli
make
sudo make install
# 或使用 OpenResty + 预编译模块
- 比 gzip 高 20-26% 压缩率
- 支持动态压缩
- 多种压缩级别
- 浏览器广泛支持
配置示例
http { brotli on; brotli_comp_level 6; brotli_types text/plain text/css application/json application/javascript text/xml application/xml; # 同时支持 gzip(兼容旧浏览器) gzip on; }
⚙️ 功能扩展模块(知名度 ★★★☆☆)
nginx-upstream-fair NO.5
nginx-upstream-fair 提供智能负载均衡算法, 根据后端服务器的实时负载情况动态分配请求,避免请求堆积在慢服务器上。
📦 安装方式
# 编译安装
git clone https://github.com/gnosek/nginx-upstream-fair
./configure --add-module=/path/to/nginx-upstream-fair
make
sudo make install
- 按后端负载分配
- 避免慢服务器堆积
- 权重配置支持
配置示例
upstream backend { fair; server 192.168.1.1:8080; server 192.168.1.2:8080; server 192.168.1.3:8080; } server { location / { proxy_pass http://backend; } }
ngx_http_geoip2_module NO.6
GeoIP2 模块提供基于 IP 的地理位置识别功能, 可以根据访客 IP 判断国家、地区、城市等信息,用于区域限制、内容本地化等场景。
📦 安装方式
# 需要 MaxMind GeoIP2 数据库
sudo apt install -y libmaxminddb-dev libmaxminddb0
# 编译模块
git clone https://github.com/leev/ngx_http_geoip2_module
./configure --add-module=/path/to/ngx_http_geoip2_module
make
sudo make install
# 下载 GeoIP2 数据库
wget https://github.com/P3TERX/GeoLite.mmdb/raw/download/GeoLite2-Country.mmdb
- IP 地理位置识别
- 支持国家/地区/城市
- ISP 和网络类型识别
- 低内存占用
配置示例
http { geoip2 /etc/nginx/GeoLite2-Country.mmdb { auto_reload 5m; $geoip2_data_country_code country iso_code; } # 只允许中国访问 location / { allow CN; deny all; } }
🤖 AI 与机器学习模块(新兴领域)
lua-resty-ai 🤖 AI 集成
lua-resty-ai 是一个 Lua 库集合,用于在 OpenResty/Nginx 中轻松集成 AI 服务。 支持调用 OpenAI、Claude、Ollama 等主流 AI 平台的 API,实现智能请求处理、内容生成、语义分析等功能。
📦 安装方式
# 使用 luarocks 安装
luarocks install lua-resty-ai
# 或从 GitHub 克隆
git clone https://github.com/your-org/lua-resty-ai.git
cp lua-resty-ai/lib/resty/ai.lua /usr/local/openresty/lualib/resty/
- 支持 OpenAI/GPT 系列
- 支持 Claude、Ollama 等
- 简单的 API 封装
- 非阻塞异步调用
- 流式响应支持
- 自动重试机制
配置示例 - AI 请求分析
location /chat { content_by_lua_block { local ai = require("resty.ai") local client = ai:new({ provider = "openai", api_key = "sk-..." }) local res = client:chat({ model = "gpt-3.5-turbo", messages = { {role = "user", content = ngx.var.arg_question} } }) ngx.say(res.choices[1].message.content) } }
ngx_http_waf_module (AI 增强版) 🛡️ AI 安全
ngx_http_waf_module AI 增强版 是传统 WAF 模块的智能化升级版本。 通过集成机器学习模型,可以智能识别 SQL 注入、XSS、CSRF 等攻击模式, 比传统规则匹配更准确,误报率更低。
📦 安装方式
# 编译安装(需要 ONNX Runtime)
git clone https://github.com/loco0x1/nginx-waf-ai
cd nginx-waf-ai
./configure --add-module=/path/to/nginx-waf-ai --with-ai-support
make
sudo make install
# 下载预训练模型
wget https://models.example.com/waf-ai-model.onnx
- AI 模型识别攻击
- 低误报率
- 自学习更新
- 实时威胁检测
- 行为分析
- IP 信誉评分
配置示例
http { waf_ai_enabled on; waf_ai_model_path "/etc/nginx/waf-ai-model.onnx"; waf_ai_threshold 0.75; # 风险阈值 location / { waf on; waf_mode "AI"; } }
lua-resty-ml 📊 机器学习
lua-resty-ml 是一个轻量级机器学习库,专为 Nginx/OpenResty 设计。 支持流量预测、异常检测、自动限流等功能,可基于历史数据训练简单模型, 在 Nginx 层实现智能化流量管理。
📦 安装方式
# 使用 luarocks 安装
luarocks install lua-resty-ml
# 需要 Redis 支持(存储训练数据)
sudo apt install -y redis-server
- 流量趋势预测
- 异常流量检测
- 自动限流调整
- 时间序列分析
- 轻量级模型
- 在线学习
配置示例 - 智能限流
location /api/ { access_by_lua_block { local ml = require("resty.ml") local predictor = ml:new({ redis_host = "127.0.0.1", model_type = "traffic" }) -- 预测当前流量负载 local load = predictor:predict("current_load") -- 根据预测动态调整限流 if load > 0.8 then ngx.var.limit_rate = 100 -- KB/s end } proxy_pass http://backend; }
ngx_http_embedding_module 🧠 向量嵌入
ngx_http_embedding_module 为 Nginx 添加文本向量化能力, 可将请求内容转换为向量嵌入,用于语义搜索、相似度匹配、RAG(检索增强生成)等场景。 支持本地模型和远程 API 调用。
📦 安装方式
# 编译安装(需要 ONNX Runtime)
git clone https://github.com/your-org/ngx-embedding-module
./configure --add-module=/path/to/ngx-embedding-module
make
sudo make install
# 下载嵌入模型(如 bge-small)
wget https://models.example.com/bge-small.onnx
- 文本向量化
- 语义相似度计算
- 支持多种模型
- 低延迟推理
- 向量缓存
- 批量处理
配置示例 - 语义搜索
location /search { content_by_lua_block { local http = require("resty.http") -- 将查询转换为向量 local embedding_res = http:request({ url = "http://localhost:8081/embedding", method = "POST", body = ngx.encode_args({q = ngx.var.arg_q}) }) -- 使用向量进行相似度搜索 local results = search_by_vector(embedding_res.body) ngx.say(ngx.encode_json(results)) } }
💡 AI 插件集成最佳实践
🔌 本地 AI 模型部署
使用 Ollama、vLLM 等工具在本地部署开源模型, 通过 HTTP API 与 Nginx 集成,数据不出内网,适合敏感场景。
☁️ 云服务 API 集成
直接调用 OpenAI、Claude、文心一言等云服务 API, 无需维护模型,适合快速原型和中小规模应用。
⚡ 性能优化建议
使用连接池复用 AI 服务连接,设置合理超时时间, 实现降级策略(AI 服务不可用时回退到规则引擎)。
🔒 安全注意事项
API Key 使用环境变量或 Vault 管理, 对 AI 响应进行内容过滤,防止注入攻击和敏感信息泄露。
🔧 其他实用模块(知名度 ★★☆☆☆)
nginx-rtmp-module NO.7
nginx-rtmp-module 为 Nginx 添加 RTMP/HLS/DASH流媒体支持, 可以搭建直播服务器、视频点播平台。支持转码、录制、统计等功能。
📦 安装方式
# 需要 FFmpeg 支持
sudo apt install -y ffmpeg
# 编译安装
git clone https://github.com/arut/nginx-rtmp-module
./configure --add-module=/path/to/nginx-rtmp-module
make
sudo make install
- RTMP/HLS/DASH支持
- 直播推流/拉流
- 视频录制
- 实时统计
lua-resty-http NO.8
lua-resty-http 是 OpenResty 的 HTTP 客户端库, 用于在 Lua 脚本中发起 HTTP 请求,常用于 API 调用、服务间通信等场景。
📦 安装方式
# 使用 luarocks 安装
luarocks install lua-resty-http
# 或在 OpenResty 中直接使用
# 通常已预装
⚡ 性能优化模块(知名度 ★★☆☆☆)
ngx_cache_purge NO.9
ngx_cache_purge 提供 Nginx 缓存清除功能, 支持按 URL 清除特定缓存、批量清除缓存。对于需要实时更新内容的场景非常有用。
📦 安装方式
# 编译安装
git clone https://github.com/FRiCKLabs/ngx_cache_purge.git
./configure --add-module=/path/to/ngx_cache_purge
make
sudo make install
- 按 URL 清除缓存
- 支持通配符批量清除
- HTTP API 接口
- 与 proxy_cache 完美集成
配置示例
http {
proxy_cache_path
/var/cache/nginx levels=1:2 keys_zone=my_cache:10m;
server {
location
/ {
proxy_cache my_cache;
proxy_cache_purge PURGE from 127.0.0.1;
}
}
}
# 清除缓存请求
PURGE
http://example.com/image.jpg
headers-more-nginx-module NO.10
headers-more 模块允许添加、修改、清除任意 HTTP 响应头, 包括 Nginx 默认添加的头。可用于隐藏服务器信息、添加安全头、优化缓存控制等。
📦 安装方式
# 编译安装
git clone https://github.com/openresty/headers-more-nginx-module
./configure --add-module=/path/to/headers-more-nginx-module
make
sudo make install
- 添加任意响应头
- 修改已有响应头
- 清除敏感信息头
- 支持条件判断
配置示例
http { # 隐藏 Nginx 版本号 more_clear_headers Server; # 添加安全头 more_set_headers "X-Frame-Options: DENY"; more_set_headers "X-Content-Type-Options: nosniff"; more_set_headers "X-XSS-Protection: 1; mode=block"; # 修改 Content-Type more_set_headers "Content-Type: text/html; charset=utf-8"; }
echo-nginx-module NO.11
echo 模块提供类似 shell echo 的命令, 用于在 Nginx 配置中直接输出内容,无需后端服务器。非常适合测试、调试和生成简单响应。
📦 安装方式
# 编译安装
git clone https://github.com/openresty/echo-nginx-module
./configure --add-module=/path/to/echo-nginx-module
make
sudo make install
- 直接输出文本内容
- 支持变量插值
- 模拟后端响应
- 调试配置利器
配置示例
location /hello { echo "Hello, World!"; } location /info { echo "Request URI: $request_uri"; echo "Remote Addr: $remote_addr"; echo "Server Name: $server_name"; } location /sleep { echo_sleep 2; echo "Slept for 2 seconds"; }
nginx-sticky-module NO.12
nginx-sticky-module 提供基于 Cookie 的会话保持功能, 确保同一用户的请求始终转发到同一台后端服务器。适用于有状态应用。
📦 安装方式
# 编译安装
git clone https://github.com/blaettler/nginx-sticky-module
./configure --add-module=/path/to/nginx-sticky-module
make
sudo make install
- Cookie 会话保持
- 自动插入 Cookie
- 支持哈希算法
- 配置简单
配置示例
upstream backend { sticky; # 或自定义 Cookie 名称 # sticky name=route_id expires=1h domain=.example.com; server 192.168.1.1:8080; server 192.168.1.2:8080; server 192.168.1.3:8080; } server { location / { proxy_pass http://backend; } }
lua-resty-redis NO.13
lua-resty-redis 是 OpenResty 的 Redis 客户端库, 提供非阻塞的 Redis 操作,可用于缓存、会话存储、分布式锁等场景。
📦 安装方式
# 使用 luarocks 安装
luarocks install lua-resty-redis
# 或在 OpenResty 中直接使用
# 通常已预装
- 非阻塞 Redis 操作
- 支持所有 Redis 命令
- 连接池管理
- 管道支持
配置示例
location /test { content_by_lua_block { local redis = require("resty.redis") local red = redis:new() red:set_timeout(1000) local ok, err = red:connect("127.0.0.1", 6379) if ok then red:set("name", "OpenResty") local name, err = red:get("name") ngx.say("Name: ", name) end } }
nginx-auth-request-module NO.14
auth_request 模块实现基于子请求的认证机制, 将认证请求转发到外部服务,根据响应决定是否允许访问。常用于 OAuth、SSO 等场景。
📦 安装方式
# 通常已内置在标准 Nginx 中
# 如未包含,需编译安装
./configure --with-http_auth_request_module
make
sudo make install
- 外部认证服务
- 灵活的认证逻辑
- 支持 OAuth/OIDC
- 与任何认证服务集成
配置示例
server { location /private/ { auth_request /auth; } location = /auth { internal; proxy_pass http://auth-server/validate; proxy_pass_request_body off; proxy_set_header X-Original-URI $request_uri; } }
🎨 创意插件(特色功能)
ngx_http_sub_module 🎯 内容替换
sub_module 提供响应内容替换功能,类似 sed 的流式编辑器, 可以在响应发送给客户端之前替换其中的内容。用于 A/B 测试、灰度发布、内容定制等场景。
📦 安装方式
# 通常已内置在标准 Nginx 中
# 如未包含,需编译时启用
./configure --with-http_sub_module
make
sudo make install
- 流式内容替换
- 支持正则表达式
- 多次替换支持
- 性能开销低
配置示例
location / { sub_filter '<body>' '<body><script src="analytics.js"></script>'; sub_filter_once off; sub_filter_types text/html; # A/B 测试:替换不同版本 sub_filter 'version-1.0' 'version-2.0'; }
lua-resty-lock 🔒 分布式锁
lua-resty-lock 提供基于共享内存的分布式锁, 用于在 Nginx worker 进程间协调任务执行,避免并发问题。适合缓存重建、定时任务等场景。
📦 安装方式
# 使用 luarocks 安装
luarocks install lua-resty-lock
# 或在 OpenResty 中直接使用
# 通常已预装
- worker 进程间锁
- 超时自动释放
- 等待超时支持
- 轻量级实现
配置示例
location /update { content_by_lua_block { local lock = require("resty.lock") local mylock, err = lock:new() local ok, err = mylock:lock("my_key", {timeout=5}) if not ok then ngx.say("failed to lock: ", err) return end # 执行临界区代码 ngx.say("doing critical section") mylock:unlock() } }
nginx-sflow-module 📊 流量监控
sFlow 模块提供网络流量采样和导出功能, 将流量数据发送到 sFlow 收集器进行实时分析。适合大规模流量监控和网络分析。
📦 安装方式
# 编译安装
git clone https://github.com/sflow/nginx-sflow-module
./configure --add-module=/path/to/nginx-sflow-module
make
sudo make install
- 实时流量采样
- 低性能开销
- 标准 sFlow 协议
- 支持多种收集器
配置示例
http { sflow on; sflow_sampling 100; sflow_collector 192.168.1.100:6343; sflow_agent eth0; }
lua-resty-upload 📤 文件上传
lua-resty-upload 提供流式文件上传处理, 支持大文件分块上传,无需将整个文件加载到内存。适合文件服务器、图片上传等场景。
📦 安装方式
# 使用 luarocks 安装
luarocks install lua-resty-upload
# 需要 lua-resty-core 支持
- 流式上传处理
- 支持大文件
- 内存占用低
- multipart 解析
配置示例
location /upload { content_by_lua_block { local upload = require("resty.upload") local form, err = upload:new(8192) while true do local type, res, err = form:read() if type == "eof" then break end # 处理上传数据 end ngx.say("upload complete") } }
nginx-module-vts 📈 虚拟主机统计
VTS (Virtual Host Traffic Status) 模块提供详细的虚拟主机流量统计, 包括请求数、流量、响应时间等指标,并支持 JSON 格式导出。是 Nginx 原生的流量监控方案。
📦 安装方式
# 编译安装
git clone https://github.com/vozlt/nginx-module-vts
./configure --add-module=/path/to/nginx-module-vts
make
sudo make install
# 需要添加状态页面
status_format json;
- 虚拟主机级别统计
- JSON 格式导出
- 实时流量数据
- 低性能开销
配置示例
http { vhost_traffic_status_zone; server { location /status { vhost_traffic_status_display; vhost_traffic_status_format json; } } }
lua-resty-dns 🌐 DNS 解析
lua-resty-dns 提供异步 DNS 客户端, 支持 A、AAAA、CNAME、MX、SRV 等多种记录类型查询。适合动态服务发现、DNS 负载均衡等场景。
📦 安装方式
# 使用 luarocks 安装
luarocks install lua-resty-dns
# 或在 OpenResty 中直接使用
- 异步 DNS 查询
- 支持多种记录类型
- DNS 缓存支持
- 错误处理完善
配置示例
location /dns { content_by_lua_block { local resolver = require("resty.dns.resolver") local r, err = resolver:new{ nameservers = {"8.8.8.8", "8.8.4.4"} } local answers, err = r:query("example.com") for i, ans in pairs(answers) do ngx.say(ans.name, " ", ans.address) end } }
nginx-allow-deny-from-args 🔐 动态访问控制
allow-deny-from-args 允许根据请求参数动态决定访问控制规则, 实现更灵活的权限管理。适合 API 网关、多租户系统等场景。
📦 安装方式
# 使用 Lua 实现
# 通过 ngx_lua 模块动态判断
location /api {
access_by_lua_block {
local token = ngx.var.arg_token
if not validate_token(token) then
ngx.exit(403)
end
}
}
- 动态访问控制
- 基于参数判断
- 灵活权限管理
- 支持 Token 验证
📊 模块对比总览
| 模块名称 | 类型 | 知名度 | 安装难度 | 主要用途 |
|---|---|---|---|---|
| ngx_lua (OpenResty) | 脚本引擎 | ★★★★★ | ⭐⭐ | 业务逻辑、API 网关 |
| njs | 脚本引擎 | ★★★★☆ | ⭐ | 请求处理、动态响应 |
| ModSecurity | 安全 WAF | ★★★★☆ | ⭐⭐⭐⭐ | Web 应用防火墙 |
| ngx_brotli | 压缩 | ★★★★☆ | ⭐⭐⭐⭐ | 资源压缩优化 |
| nginx-upstream-fair | 负载均衡 | ★★★☆☆ | ⭐⭐⭐ | 智能负载调度 |
| ngx_http_geoip2 | 地理位置 | ★★★☆☆ | ⭐⭐⭐ | IP 地域识别 |
| nginx-rtmp-module | 流媒体 | ★★★☆☆ | ⭐⭐⭐⭐ | 直播/点播 |
| lua-resty-http | HTTP 客户端 | ★★★☆☆ | ⭐⭐ | 服务间通信 |
| ngx_cache_purge | 缓存管理 | ★★★☆☆ | ⭐⭐⭐ | 缓存清除 |
| headers-more | Header 处理 | ★★★☆☆ | ⭐⭐⭐ | 响应头管理 |
| echo | 调试工具 | ★★☆☆☆ | ⭐⭐⭐ | 测试调试 |
| nginx-sticky | 会话保持 | ★★☆☆☆ | ⭐⭐⭐ | Cookie 会话保持 |
| lua-resty-redis | Redis 客户端 | ★★★☆☆ | ⭐⭐ | 缓存/会话存储 |
| auth_request | 认证 | ★★★☆☆ | ⭐⭐ | OAuth/SSO 认证 |
| ngx_http_sub_module | 内容替换 | ★★★☆☆ | ⭐ | A/B 测试、灰度发布 |
| lua-resty-lock | 分布式锁 | ★★★☆☆ | ⭐⭐ | 并发控制、缓存重建 |
| nginx-module-vts | 流量统计 | ★★★☆☆ | ⭐⭐⭐ | 虚拟主机监控 |
| lua-resty-dns | DNS 解析 | ★★☆☆☆ | ⭐⭐ | 服务发现、DNS 负载均衡 |
| lua-resty-upload | 文件上传 | ★★☆☆☆ | ⭐⭐⭐ | 大文件流式上传 |
| nginx-sflow-module | 流量监控 | ★★☆☆☆ | ⭐⭐⭐⭐ | 大规模流量分析 |
🔨 编译安装指南
- 下载 Nginx 源码:
wget https://nginx.org/download/nginx-1.24.0.tar.gz - 解压源码:
tar -xzf nginx-1.24.0.tar.gz - 克隆第三方模块:
git clone https://github.com/xxx/module - 配置编译选项:
./configure --add-module=/path/to/module - 编译安装:
make && sudo make install
- OpenResty 官方文档:
https://openresty.org/ - Nginx 模块开发指南:
https://www.nginx.com/resources/wiki/extending/ - lua-resty 库集合:
https://github.com/openresty/lua-resty-core - Nginx 模块 GitHub 仓库:
https://github.com/nginx - OpenResty Lua 库:
https://github.com/openresty/lua-resty-*
- A/B 测试:使用
sub_module替换页面内容,快速测试不同版本 - 缓存保护:使用
lua-resty-lock防止缓存穿透和并发重建 - 多租户监控:使用
nginx-module-vts统计每个域名的流量 - 微服务架构:使用
lua-resty-dns实现动态服务发现 - 文件服务:使用
lua-resty-upload处理大文件上传