Nginx添加Lua模块
最近在学习如何在Nginx或基于Nginx开发的组件中通过Lua进行定制化的开发,完成自己的需求。一起看看吧😊
安装LuaJIT2
为Nginx添加Lua模块的前提需要安装LuaJIT,这里使用的是openresty的luajit2。
1 | git clone https://github.com/openresty/luajit2 |
完成后看到如下内容就代表安装成功了😃
1 | ==== Successfully built LuaJIT 2.1.0-beta3 ==== |
此外,需要对环境变量、链接库进行配置:
1 | export LUAJIT_LIB=/usr/local/src/LuaJIT/lib |
注意: 此处使用的是luajit2,并不是luajit,网上很多文章用的是从luajit中下载的LuaJIT-2.0.5.tar.gz,我在用LuaJIT-2.0.5测试过程中,遇到了问题:
nginx: [alert] detected a LuaJIT version which is not OpenResty’s; many optimizations will be disabled and performance will be compromised (see https://github.com/openresty/luajit2 for OpenResty’s LuaJIT or, even better, consider using the OpenResty releases from https://openresty.org/en/download.html)
Nginx Module
准备两个模块:
- ngx_devel_kit: NDK(nginx development kit)模块是一个拓展nginx服务器核心功能的模块,第三方模块开发可以基于它来快速实现。NDK提供函数和宏处理一些基本任务,减轻第三方模块开发的代码量。
- lua-nginx-module: 将Lua的功能嵌入到Nginx HTTP服务器中。
1 | mkdir ngx_module |
目前lua-nginx-module
的最新release版本是v0.10.19,使用该版本在测试过程中遇到报错如下:
1 | nginx: [alert] failed to load the 'resty.core' module (https://github.com/openresty/lua-resty-core); ensure you are using an OpenResty release from https://openresty.org/en/download.html (reason: module 'resty.core' not found: |
在下面的链接中找到了答案,使用v0.10.14版本即可:
1 | https://github.com/openresty/lua-resty-core/issues/248 |
编译Nginx
1 | $ https://nginx.org/download/nginx-1.18.0.tar.gz |
访问测试
在nginx.conf
中server
代码块里加入如下代码:
1 | location /hello_lua { |
启动Nginx(此处有需要可以做软链接、系统启动等,我这里只是做测试用):
1 | /usr/local/src/nginx/sbin |
通过curl进行测试:
1 | curl http://127.0.0.1/hello_lua |
动态加载
编译模块
Nginx 1.9.11开始增加了加载动态模块支持,可以通过修改配置文件reload增加、卸载模块。这里测试下动态加载,使用add-dynamic-module
选项。
1 | ./configure --prefix=/usr/local/src/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_realip_module --with-http_sub_module --with-http_gzip_static_module --with-http_v2_module --with-pcre --with-ld-opt=-Wl,-rpath,/usr/local/src/LuaJIT/lib --add-dynamic-module=/usr/local/src/ngx_module/ngx_devel_kit-0.3.1 --add-dynamic-module=/usr/local/src/ngx_module/lua-nginx-module-0.10.14 |
编译安装以后,可以看到modules中的so库:
1 | $ ls -lrt modules/ |
编辑配置
在nginx.conf文件的main context中增加以下两行:
1 | load_module /usr/local/src/nginx/modules/ndk_http_module.so; |
并在server块添加访问测试中的测试配置后,启动Nginx,效果一致。
参考
1、http://nginx.org/en/docs/ngx_core_module.html#load_module
2、https://github.com/openresty/lua-nginx-module#building-as-a-dynamic-module