OpenResty本身就是增强版Nginx,集成了Nginx核心、LuaJIT及redis/mysql/ssl/http2等模块,开箱即用;无需手动编译ngx_lua模块,避免依赖冲突与维护成本。

不需要“集成”OpenResty到Nginx——OpenResty本身就是增强版的Nginx,它不是插件,而是Nginx + LuaJIT + 一整套常用模块(redis、mysql、ssl、http2、stream等)的预编译集成平台。想用Lua扩展Nginx功能,直接安装OpenResty即可,无需在原有Nginx上额外加模块。
为什么不用单独给Nginx加ngx_lua模块
手动编译Nginx并添加ngx_lua模块步骤繁琐,需自行解决依赖(如PCRE、OpenSSL、zlib)、Lua版本兼容性、LuaJIT链接方式等问题;而OpenResty已默认内置稳定版本的LuaJIT和lua-nginx-module,并完成全部适配与性能调优。生产环境更推荐开箱即用的OpenResty,避免隐性bug和维护成本。
快速安装OpenResty(主流Linux)
Ubuntu/Debian:
- 执行以下命令添加官方仓库并安装
sudo apt-get install -y software-properties-common
sudo add-apt-repository -y ppa:openresty/ppa
sudo apt-get update && sudo apt-get install -y openresty openresty-resty
CentOS/RHEL:
- 先启用EPEL,再添加OpenResty官方YUM源
sudo yum install -y epel-release
sudo yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
sudo yum install -y openresty openresty-resty
验证Lua是否就绪
安装完成后,检查配置是否加载Lua支持:
- 运行
openresty -V,输出中应含--add-module=.../lua-nginx-module - 启动默认服务:
sudo openresty(配置文件位于/usr/local/openresty/nginx/conf/nginx.conf) - 写一个测试location:
location /hello {
default_type text/plain;
content_by_lua_block {
ngx.say("Hello from OpenResty!")
}
}
访问http://localhost/hello,返回文本即说明Lua运行正常。
关键配置项不能漏
在http块中务必设置Lua运行环境:
-
lua_package_path '/usr/local/openresty/lualib/?.lua;;';—— 指定Lua模块搜索路径 -
lua_package_cpath '/usr/local/openresty/lualib/?.so;;';—— 指定C模块(如luasocket、lua-resty-redis)路径 -
init_by_lua_block用于全局初始化(如加载共享内存、预编译正则) -
init_worker_by_lua_block适合启动定时器、连接池预热等worker级操作











