1. OpenResty简介与版本说明
OpenResty是一个基于Nginx与LuaJIT的高性能Web平台,由章亦春开发。它将标准Nginx核心、LuaJIT、大量第三方Nginx模块以及大部分外部依赖整合在一起,形成一个功能强大的网络应用服务器。更多学习教程www.fgedu.net.cn。
OpenResty通过Lua脚本扩展Nginx功能,可以实现复杂的业务逻辑处理,非常适合构建动态Web应用、API网关、Web应用防火墙等场景。学习交流加群风哥微信: itpux-com。OpenResty的核心优势在于其高性能和灵活性,能够处理数万并发连接。
OpenResty核心组件:
– LuaJIT:高性能Lua即时编译器
– ngx_lua模块:Nginx Lua脚本支持
– lua-resty-*:丰富的Lua库集合
– OpenSSL:SSL/TLS加密支持
– PCRE:正则表达式支持
– zlib:压缩库支持
– 其他第三方模块:如ngx_http_upstream_check_module等
OpenResty应用场景:
– Web应用防火墙(WAF):安全防护、攻击检测
– 负载均衡:七层负载均衡、健康检查
– 动态路由:基于请求内容的智能路由
– 缓存服务:高效的内容缓存
– 微服务架构:服务发现、熔断降级
– 实时通信:WebSocket代理、长连接管理
– 日志分析:实时日志处理和分析
2. OpenResty版本选择与下载地址
OpenResty版本号格式为:Nginx版本.OpenResty版本,如1.29.2.3表示基于Nginx 1.29.x的OpenResty第3个版本。
OpenResty版本状态:
1.29.2.3 2026-03-25 1.29.x 最新稳定版
1.29.2.1 2026-01-04 1.29.x 稳定版
1.27.1.2 2025-03-14 1.27.x 长期支持版
1.27.1.1 2024-10-16 1.27.x 稳定版
1.25.3.2 2024-07-19 1.25.x 维护版
1.25.3.1 2024-01-04 1.25.x 维护版
1.21.4.4 2024-07-19 1.21.x 旧版支持
OpenResty 1.29.2.3主要更新:
– OpenSSL升级到3.4.1
– PCRE升级到10.44
– LuaJIT性能优化
– ngx_lua模块bug修复
– stream-lua模块新功能
– 安全漏洞修复
官方下载地址:
下载页面:https://openresty.org/cn/download.html
源码仓库:https://github.com/openresty/openresty
Docker镜像:https://hub.docker.com/r/openresty/openresty
文档中心:https://openresty.org/cn/documentation.html
3. OpenResty下载方式详解
方式一:源码编译安装(推荐生产环境)
$ cd /fgeudb/software
$ wget https://openresty.org/download/openresty-1.29.2.3.tar.gz
输出示例如下:
–2026-04-04 10:00:00– https://openresty.org/download/openresty-1.29.2.3.tar.gz
Resolving openresty.org (openresty.org)… 107.155.87.77
Connecting to openresty.org (openresty.org)|107.155.87.77|:443… connected.
HTTP request sent, awaiting response… 200 OK
Length: 5662345 (5.4M) [application/octet-stream]
Saving to: ‘openresty-1.29.2.3.tar.gz’
openresty-1.29.2.3.tar.gz 100%[======================================================================>] 5.40M 8.5MB/s in 0.6s
2026-04-04 10:00:01 (8.5 MB/s) – ‘openresty-1.29.2.3.tar.gz’ saved [5662345/5662345]
解压源码包:
$ tar -zxvf openresty-1.29.2.3.tar.gz -C /fgeudb/
安装编译依赖:
# yum install -y gcc pcre-devel openssl-devel make curl
或Ubuntu/Debian:
# apt install -y build-essential libpcre3 libpcre3-dev libssl-dev curl
方式二:官方仓库安装(推荐)
# yum install -y yum-utils
# yum-config-manager –add-repo https://openresty.org/package/centos/openresty.repo
安装OpenResty:
# yum install -y openresty
输出示例如下:
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
Resolving Dependencies
–> Running transaction check
—> Package openresty.x86_64 0:1.29.2.3-1.el7 will be installed
–> Finished Dependency Resolution
Dependencies Resolved
================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
openresty x86_64 1.29.2.3-1.el7 openresty 5.2 M
Transaction Summary
================================================================================
Install 1 Package
Total download size: 5.2 M
Installed size: 15 M
Downloading packages:
openresty-1.29.2.3-1.el7.x86_64.rpm | 5.2 MB 00:00:02
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : openresty-1.29.2.3-1.el7.x86_64 1/1
Verifying : openresty-1.29.2.3-1.el7.x86_64 1/1
Installed:
openresty.x86_64 0:1.29.2.3-1.el7
Complete!
Ubuntu/Debian安装官方仓库:
# apt install -y curl gnupg2 lsb-release
# wget -qO – https://openresty.org/package/pubkey.gpg | apt-key add –
# echo “deb http://openresty.org/package/ubuntu $(lsb_release -sc) main” | tee /etc/apt/sources.list.d/openresty.list
# apt update
# apt install -y openresty
验证安装:
$ openresty -V
输出示例如下:
nginx version: openresty/1.29.2.3
built by gcc 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04)
built with OpenSSL 3.4.1
TLS SNI support enabled
configure arguments: –prefix=/usr/local/openresty/nginx …
方式三:Docker容器部署
$ docker pull openresty/openresty:1.29.2.3-0-alpine
输出示例如下:
1.29.2.3-0-alpine: Pulling from openresty/openresty
Digest: sha256:abc123def456…
Status: Downloaded newer image for openresty/openresty:1.29.2.3-0-alpine
启动OpenResty容器:
$ docker run –name openresty-web \
-p 80:80 \
-p 443:443 \
-v /fgeudb/openresty/conf:/usr/local/openresty/nginx/conf:ro \
-v /fgeudb/openresty/lua:/usr/local/openresty/lua:ro \
-v /fgeudb/openresty/logs:/usr/local/openresty/nginx/logs \
-d openresty/openresty:1.29.2.3-0-alpine
输出示例如下:
abc123def456789…
查看容器状态:
$ docker ps | grep openresty
输出示例如下:
abc123def456 openresty/openresty:1.29.2.3-0-alpine “/usr/local/openresty…” 10 seconds ago Up 9 seconds 0.0.0.0:80->80/tcp openresty-web
方式四:Windows安装
$ wget https://openresty.org/download/openresty-1.29.2.1-win64.zip
解压到指定目录:
C:\> unzip openresty-1.29.2.1-win64.zip -d C:\openresty
启动OpenResty:
C:\> cd C:\openresty
C:\openresty> nginx.exe
停止OpenResty:
C:\openresty> nginx.exe -s stop
重载配置:
C:\openresty> nginx.exe -s reload
4. OpenResty安装部署实战
步骤1:编译安装OpenResty
# groupadd openresty
# useradd -g openresty -s /sbin/nologin -M openresty
配置编译选项:
$ cd /fgeudb/openresty-1.29.2.3
$ ./configure \
–prefix=/fgeudb/openresty \
–user=openresty \
–group=openresty \
–with-http_ssl_module \
–with-http_v2_module \
–with-http_realip_module \
–with-http_stub_status_module \
–with-http_gzip_static_module \
–with-pcre-jit \
–with-stream \
–with-stream_ssl_module \
–with-luajit
输出示例如下:
platform: linux (linux)
cp -rp bundle/ build
cd build
cd LuaJIT-2.1-20240815
gmake -j4 PREFIX=/fgeudb/openresty/luajit
…
Type the following commands to build and install:
make
sudo make install
编译安装:
$ make -j$(nproc)
# make install
输出示例如下:
make -C build -f Makefile install
make[1]: Entering directory ‘/fgeudb/openresty-1.29.2.3/build’
…
make[1]: Leaving directory ‘/fgeudb/openresty-1.29.2.3/build’
步骤2:配置systemd服务
# vi /etc/systemd/system/openresty.service
[Unit]
Description=OpenResty – high performance web platform
Documentation=https://openresty.org/
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/fgeudb/openresty/nginx/logs/nginx.pid
ExecStartPre=/fgeudb/openresty/nginx/sbin/nginx -t -c /fgeudb/openresty/nginx/conf/nginx.conf
ExecStart=/fgeudb/openresty/nginx/sbin/nginx -c /fgeudb/openresty/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
重载服务配置:
# systemctl daemon-reload
启动服务:
# systemctl start openresty
设置开机自启:
# systemctl enable openresty
查看服务状态:
# systemctl status openresty
输出示例如下:
● openresty.service – OpenResty – high performance web platform
Loaded: loaded (/etc/systemd/system/openresty.service; enabled)
Active: active (running) since Fri 2026-04-04 10:05:00 CST; 10s ago
Main PID: 12345 (nginx)
CGroup: /system.slice/openresty.service
├─12345 nginx: master process /fgeudb/openresty/nginx/sbin/nginx
└─12346 nginx: worker process
步骤3:配置nginx.conf主配置文件
# vi /fgeudb/openresty/nginx/conf/nginx.conf
user openresty;
worker_processes auto;
worker_rlimit_nofile 65535;
error_log /fgeudb/openresty/nginx/logs/error.log warn;
pid /fgeudb/openresty/nginx/logs/nginx.pid;
events {
use epoll;
worker_connections 65535;
multi_accept on;
}
http {
include mime.types;
default_type application/octet-stream;
server_tokens off;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
client_max_body_size 100m;
gzip on;
gzip_min_length 1k;
gzip_types text/plain text/css application/json application/javascript;
lua_package_path “/fgeudb/openresty/lua/?.lua;;”;
lua_package_cpath “/fgeudb/openresty/lua/?.so;;”;
lua_code_cache on;
lua_max_pending_timers 1024;
lua_max_running_timers 256;
init_by_lua_block {
require “resty.core”
}
log_format main ‘$remote_addr – $remote_user [$time_local] “$request” ‘
‘$status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” “$http_x_forwarded_for” ‘
‘rt=$request_time uct=”$upstream_connect_time”‘;
access_log /fgeudb/openresty/nginx/logs/access.log main buffer=32k flush=5s;
include /fgeudb/openresty/nginx/conf/conf.d/*.conf;
}
5. OpenResty Lua开发基础
步骤1:创建基础Lua脚本
# mkdir -p /fgeudb/openresty/lua
创建Hello World脚本:
# vi /fgeudb/openresty/lua/hello.lua
local function main()
ngx.say(“Hello, OpenResty!”)
ngx.say(“Server: “, ngx.var.server_name)
ngx.say(“Time: “, ngx.now())
end
main()
创建配置引用:
# vi /fgeudb/openresty/nginx/conf/conf.d/hello.conf
server {
listen 80;
server_name lua.fgedu.net.cn;
location /hello {
default_type ‘text/plain’;
content_by_lua_file /fgeudb/openresty/lua/hello.lua;
}
}
测试访问:
$ curl http://192.168.1.51/hello
输出示例如下:
Hello, OpenResty!
Server: lua.fgedu.net.cn
Time: 1712204400
步骤2:Lua共享字典配置
http {
lua_shared_dict cache 128m;
lua_shared_dict limit 10m;
lua_shared_dict session 10m;
}
使用共享字典:
# vi /fgeudb/openresty/lua/cache.lua
local cache = ngx.shared.cache
local function set_cache(key, value, ttl)
local ok, err = cache:set(key, value, ttl or 60)
if not ok then
ngx.log(ngx.ERR, “failed to set cache: “, err)
return false
end
return true
end
local function get_cache(key)
local value, err = cache:get(key)
if err then
ngx.log(ngx.ERR, “failed to get cache: “, err)
return nil
end
return value
end
return {
set = set_cache,
get = get_cache
}
步骤3:Lua连接MySQL
# vi /fgeudb/openresty/lua/mysql.lua
local mysql = require “resty.mysql”
local function get_db_connection()
local db, err = mysql:new()
if not db then
ngx.log(ngx.ERR, “failed to instantiate mysql: “, err)
return nil, err
end
db:set_timeout(1000)
local ok, err, errcode, sqlstate = db:connect{
host = “192.168.1.51”,
port = 3306,
database = “fgedudb”,
user = “fgedu”,
password = “fgedu123”,
charset = “utf8mb4”,
max_packet_size = 1024 * 1024,
}
if not ok then
ngx.log(ngx.ERR, “failed to connect: “, err, ” “, errcode, ” “, sqlstate)
return nil, err
end
return db
end
local function query(sql)
local db = get_db_connection()
if not db then
return nil, “failed to get connection”
end
local res, err, errcode, sqlstate = db:query(sql)
db:close()
return res, err
end
return {
connect = get_db_connection,
query = query
}
6. OpenResty API网关配置
配置API网关路由
# vi /fgeudb/openresty/nginx/conf/conf.d/api-gateway.conf
upstream backend_api {
server 192.168.1.51:8080 weight=3;
server 192.168.1.52:8080 weight=2;
server 192.168.1.53:8080 weight=1;
keepalive 32;
}
server {
listen 80;
server_name api.fgedu.net.cn;
location / {
access_by_lua_block {
local limit = require “resty.limit.req”
local lim, err = limit.new(“limit”, 100, 200)
if not lim then
ngx.log(ngx.ERR, “failed to instantiate a resty.limit.req object: “, err)
return ngx.exit(500)
end
local key = ngx.var.binary_remote_addr
local delay, err = lim:incoming(key, true)
if not delay then
if err == “rejected” then
return ngx.exit(429)
end
return ngx.exit(500)
end
if delay >= 0.001 then
ngx.sleep(delay)
end
}
proxy_pass http://backend_api;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection “”;
}
location /health {
default_type ‘application/json’;
content_by_lua_block {
ngx.say(‘{“status”: “ok”}’)
}
}
}
配置JWT认证
# vi /fgeudb/openresty/lua/jwt.lua
local jwt = require “resty.jwt”
local function verify_token(token)
local secret = “fgedu-secret-key-2026”
local jwt_obj = jwt:verify(secret, token)
if not jwt_obj.verified then
ngx.log(ngx.ERR, “jwt verification failed: “, jwt_obj.reason)
return false, jwt_obj.reason
end
return true, jwt_obj.payload
end
local function auth()
local auth_header = ngx.var.http_authorization
if not auth_header then
return ngx.exit(401)
end
local token = auth_header:match(“Bearer%s+(.+)”)
if not token then
return ngx.exit(401)
end
local ok, payload = verify_token(token)
if not ok then
return ngx.exit(401)
end
ngx.ctx.user = payload
end
return {
verify = verify_token,
auth = auth
}
7. OpenResty WAF配置
配置基础WAF规则
# vi /fgeudb/openresty/lua/waf.lua
local _M = {}
local function check_sql_injection(str)
local patterns = {
“union.*select”,
“select.*from”,
“insert.*into”,
“delete.*from”,
“update.*set”,
“drop.*table”,
“exec%(“,
“execute%(“,
“–“,
“/%*.*%*/”,
}
for _, pattern in ipairs(patterns) do
if ngx.re.match(str, pattern, “isjo”) then
return true
end
end
return false
end
local function check_xss(str)
local patterns = {
“
