nginx动态添加lua模块
添加lua模块,分静态和动态。静态需要先卸载老nginx再包含lua模块做源码编译,造成nginx不可用,故不考虑。
动态则是使用相同版本的nginx源码编译,导出lua模块的动态so,再复制到老nginx的modules内,服务重启即可。
主要参考 https://www.jianshu.com/p/077208fc838c 但换了版本和源。
0 前期准备
- 切换root账号
- cd进/tmp
- yum -y install pcre-devel zlib-devel
1 下载源码
下载下面的源码到tmp并解压。注意用ngnix -V
选择原来的nginx版本
- wget https://codeload.github.com/openresty/luajit2/tar.gz/refs/tags/v2.1-20230911
- wget https://github.com/simpl/ngx_devel_kit/archive/v0.3.3.tar.gz
- wget https://github.com/openresty/lua-nginx-module/archive/v0.10.14.tar.gz
- wget https://nginx.org/download/nginx-1.20.1.tar.gz
2 编译安装luajit2
cd luajit2-2.1-20230911/
make && make install PREFIX=/usr/local/LuaJIT
echo "export LUAJIT_LIB=/usr/local/LuaJIT/lib">>/etc/profile
echo "export LUAJIT_INC=/usr/local/LuaJIT/include/luajit-2.1">>/etc/profile
source /etc/profile
echo "$LUAJIT_LIB" >> /etc/ld.so.conf
ldconfig
echo $LUAJIT_LIB
3 动态lua模块编入nginx源码
避免覆盖原来的nginx,需要指定另一个文件夹/tmp/tmp_nginx。 或者不install,但为了避免手抖,还是建议替换文件夹
动态编译的就是 --add-dynamic-module
cd nginx-1.20.1
./configure --prefix=/tmp/tmp_nginx --sbin-path=/tmp/tmp_nginx/nginx --conf-path=/tmp/tmp_nginx/nginx.conf --pid-path=/tmp/tmp_nginx/nginx.pid --with-http_stub_status_module --with-file-aio --with-http_realip_module --with-compat --add-dynamic-module=/tmp/lua-nginx-module-0.10.14 --add-dynamic-module=/tmp/ngx_devel_kit-0.3.3
make -j4
4 复制动态模块并重启原nginx
cd ~/
cp /tmp/nginx-1.20.1/objs/*.so /usr/lib64/nginx/modules/
touch /usr/share/nginx/modules/mod-lua.conf
echo 'load_module "/usr/lib64/nginx/modules/ndk_http_module.so";'>>/usr/share/nginx/modules/mod-lua.conf
echo 'load_module "/usr/lib64/nginx/modules/ngx_http_lua_module.so";'>>/usr/share/nginx/modules/mod-lua.conf
service nginx restart
5 编写触发脚本
修改/etc/nginx/nginx.conf
- lua的字符串拼接是
..
- 仅当外网访问(host是xxx.com) get请求,路径为/zzz/开头的,才会触发另一个链接
- lua_proxy下的是被触发的接口
location /lua_proxy {
proxy_pass http://192.168.0.4:8095/yyy;
}
access_by_lua_block {
if "GET" == ngx.req.get_method() and "xxx.com" == ngx.req.get_headers()["Host"] and ngx.var.uri==string.match(ngx.var.uri,'^/zzz/.*') then
# ngx.log(ngx.ERR, "lua: access "..ngx.req.get_headers()["Host"]);
ngx.location.capture("/lua_proxy"..ngx.var.uri);
end;
}