生产环境为了方便查看接口请求和响应,便于调试错误。
可以在nginx反向代理端及时查看接口信息。
需要ngx_lua模块支持
首先定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] - -'
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
#使用$request记录请求信息,$$request_body 请求body $request_body记录response信息
log_format api_log_format '$remote_addr - $remote_user [$time_local] "$request" $request_body '
'$status $body_bytes_sent $resp_body'
'"$http_user_agent" "$http_x_forwarded_for"';
配置虚拟server
upstream api_zuobin {
server 218.17.158.76:8100;
}
server {
listen 8100;
#先定义response body
set $resp_body "";
access_log logs/api_zuobin.access.log api_log_format;
error_log logs/api_zuobin.error.log ;
root html;
index index.html index.htm;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_max_temp_file_size 0;
proxy_connect_timeout 10;
proxy_send_timeout 20;
proxy_read_timeout 30;
proxy_buffer_size 32k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 32k;
proxy_temp_file_write_size 32k;
location ~ /api/ {
lua_need_request_body on;
#string.sub(ngx.arg[1], 1, 1000) 1000是response记录长度
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 ';
proxy_pass http://api_zuobin;
}
location / {
proxy_pass http://api_zuobin;
}
}
原文链接:Nginx反向代理记录api请求和响应详细信息,转载请注明来源!