安装LuaJIT
# 下载
wget http://luajit.org/download/LuaJIT-2.0.5.tar.gz
tar -xvf LuaJIT-2.0.5.tar.gz && cd LuaJIT-2.0.5/
make && make install
下载Lua模块
wget https://github.com/openresty/lua-nginx-module/archive/v0.10.10.tar.gz
tar -xvf v0.10.10.tar.gz
环境变量
export LUAJIT_LIB=/usr/local/lib
export LUAJIT_INC=/usr/local/include/luajit-2.0
Nginx编译整合Lua模块
# 注意Nginx和Lua所在的位置
cd nginx-1.18.5 # Nginx源码包位置
./configure --prefix=/usr/local/nginx --add-module=../lua-nginx-module-0.10.10/ # /usr/local/nginx是Nginx安装位置
make # 编译完成不安装
echo $?
替换Nginx启动程序
cp objs/nginx /usr/local/nginx/sbin/nginx
安装中遇到的问题
1、sh nginx -V 出现以下错误:
error while loading shared libraries: libluajit-5.1.so.2: cannot open shared object file: No such file or directory
解决:
ln -s /usr/local/lib/libluajit-5.1.so.2 /lib64/libluajit-5.1.so.2
ldconfig
2、make编译错误:“cc1: all warnings being treated as errors”
解决:
进入Nginx源码包目录objs下,vim Makefile
将CFLAGS = -pipe -O -W -Wall -Wpointer-arith -Wno-unused -Werror -g 后的 -Werror -g 去掉,
变成:
CFLAGS = -pipe -O -W -Wall -Wpointer-arith -Wno-unused
wq保存退出 重新make 即可
配置打印请求和响应参数
方法一
1、配置log格式:
log_format lua1 ' [$time_local] "$request" $status \n'
'req_header:"$req_header" \n req_body:"$request_body" \n'
'resp_header:"$resp_header" \n resp_body:"$resp_body"\n\n';
log_format lua2 '$remote_addr [$time_local] $request $status $body_bytes_sent
$request_body $resp_body';
2、配置文件location:加在proxy_pass语句下面
#请求响应头部
set $req_header "";
set $resp_header "";
header_filter_by_lua '
local h1 = ngx.req.get_headers()
for k1, v1 in pairs(h1) do
ngx.var.req_header=ngx.var.req_header..k1..": "..v1
end
local h = ngx.resp.get_headers()
for k, v in pairs(h) do
ngx.var.resp_header=ngx.var.resp_header..k..": "..v
end
';
lua_need_request_body on;
#响应头部
set $resp_body "";
body_filter_by_lua '
local resp_body = string.sub(ngx.arg[1], 1, 1000)
ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_body
if ngx.arg[2] then
ngx.var.resp_body = ngx.ctx.buffered
end
';
方法二
更简单的方案,打印到错误日志里面。但是这种会失去其它log_format的指导作用,这个方式还未尝试。
error_log /tmp/nginx.resp.info.log lua2;
location / {
proxy_pass http://blog.laifu.life/;
body_filter_by_lua 'ngx.log(ngx.INFO, ngx.arg[1])';
}