需源码编译集成lua-nginx-module:先装LuaJIT并验证,再configure指定模块路径和头文件/库路径,make安装后通过content_by_lua_block验证。

在 Linux 下通过源码编译 Nginx 并集成 OpenResty 的 Lua 模块(即 lua-nginx-module),核心是让 Nginx 支持嵌入 Lua 脚本,实现高性能、可编程的 Web 服务逻辑。这不是简单加个动态模块,而是需要在编译阶段将 Lua 支持“ baked in”。OpenResty 提供了完整打包的方案,但若你坚持从头编译原生 Nginx + 官方 lua-nginx-module,以下步骤清晰可行。
准备依赖和基础环境
确保系统已安装编译工具链及必要库:
- gcc、make、perl、libpcre3-dev(或 pcre-devel)、zlib1g-dev(或 zlib-devel)、openssl-dev(或 openssl-devel)
- Lua 解释器:推荐使用 Lua 5.1 或 LuaJIT(OpenResty 默认用 LuaJIT,性能更好;若选 Lua 5.1,需确保
lua5.1及liblua5.1-dev已安装) - 下载 Nginx 源码(如 nginx-1.24.0)、lua-nginx-module(如 v0.10.25)、LuaJIT(如 v2.1-20230320)或 lua5.1 源码
编译并安装 LuaJIT(推荐)
OpenResty 和大多数生产场景倾向 LuaJIT —— 它比标准 Lua 快数倍,且与 nginx-module 兼容性好:
- 解压 LuaJIT 源码,进入目录执行:
make && sudo make install - 默认安装到
/usr/local,头文件在/usr/local/include/luajit-2.1,库文件在/usr/local/lib/libluajit-5.1.a - 确认可用:
luajit -v应输出版本号
配置并编译 Nginx(含 lua-nginx-module)
关键在于 ./configure 阶段正确指定 LuaJIT 路径和模块位置:
- 假设 lua-nginx-module 解压在
~/src/lua-nginx-module-0.10.25,LuaJIT 安装在/usr/local - 执行 configure(精简常用选项):
./configure \ --prefix=/usr/local/nginx \ --with-http_ssl_module \ --with-http_realip_module \ --with-http_v2_module \ --add-module=~/src/lua-nginx-module-0.10.25 \ --with-ld-opt="-Wl,-rpath,/usr/local/lib" \ --with-cc-opt="-I/usr/local/include/luajit-2.1"
-
--add-module指向 lua-nginx-module 源码目录(不是 .so 文件) -
--with-cc-opt告诉编译器 LuaJIT 头文件位置 -
--with-ld-opt确保运行时能定位 libluajit(尤其避免 “cannot open shared object file: libluajit-5.1.so.2” 错误) - 接着运行:
make && sudo make install
验证 Lua 模块是否生效
编辑 /usr/local/nginx/conf/nginx.conf,在 http 块中添加最小测试配置:
lua_package_path "/path/to/your/lua/?.lua;;";
server {
listen 8080;
location /hello {
content_by_lua_block {
ngx.say("Hello from Lua in Nginx!")
}
}
}
- 保存后执行:
/usr/local/nginx/sbin/nginx -t检查语法 - 启动:
/usr/local/nginx/sbin/nginx - 访问
curl http://localhost:8080/hello,应返回对应字符串 - 若报错 “unknown directive 'content_by_lua_block'”,说明模块未正确编译进 Nginx,重点检查 configure 参数和路径是否拼写准确
不复杂但容易忽略:Nginx 不支持运行时加载 lua-nginx-module,必须源码编译集成;LuaJIT 路径、RPATH 设置、模块路径三者任一出错都会导致失败。稳住节奏,逐项验证,就能跑通。

















