基于nginx打印返回值,此功能在nginx内置的功能中没有,需要安装第三方模块ngx_lua及相关模块
1. 安装LuaJIT
此模块需要Lua语言,所以需要安装相应的Lua语言包,下载后解压并安装
wget http://luajit.org/download/LuaJIT-2.0.2.tar.gz
tar -xzvf LuaJIT-2.0.2.tar.gz
cd LuaJIT-2.0.2
make
make install
导入环境变量,告诉nginx去哪里找luajit
export LUAJIT_LIB=/usr/local/lib
export LUAJIT_INC=/usr/local/include/luajit-2.0
2. 下载及解压nginx lua模块
cd /etc/nginx/modules
wget https://github.com/openresty/lua-nginx-module/archive/v0.10.9rc7.tar.gz
tar -zxvf v0.10.9rc7.tar.gz
3. 安装nginx或已安装
4. 进入到nginx源码文件夹下,将新的模块编译进去
./configure --add-module=/usr/src/lua-nginx-module-0.10.9rc7
可通过./nginx -V 查看是否添加成功如图
./configure 命令正确执行之后,重新编译nginx
make -j2
make install
5. 配置nginx配置文件
修改nginx.conf,在log_format中添加response body的变量[ resp_body:"$resp_body"]
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" resp_body:"$resp_body" ';
access_log /var/log/nginx/access.log main;
然后server里面赋值:
server {
listen 80;
server_name localhost;
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
';
# 根路径
location / {
root /home/temp/;
index index.html index.htm;
}
}
执行./nginx -t 检查配置是否正确 若报以下错误
nginx: error while loading shared libraries: libluajit-5.1.so.2: cannot open shared object file: No such file or directory
出现这个错误,是变量没有写进去,所以就添加下变量:
cat /etc/ld.so.conf
include ld.so.conf.d/*.conf
echo “/usr/local/lib” >> /etc/ld.so.conf
ldconfig
然后就正常了。
./nginx -s reload 重启