1.现象
在nginx中想利用$request_body命令获取post请求的body参数,并落日志,但是发现该变量值为空,查看官网中对$request_body的描述如下:
$request_body
request body
The variable’s value is made available in locations processed by the proxy_pass, fastcgi_pass, uwsgi_pass, and scgi_pass directives when the request body was read to a memory buffer.
意思是只有location中用到proxy_pass,fastcgi_pass,scgi_pass命令时,该变量才有值。
2.使用proxy_pass,fastcgi_pass, scgi_pass等命令获取$request_body值
试了下用proxy_pass,的确可以。配置如下:
worker_processes1;
#nginx worker 数量
error_log logs/error.log;
#指定错误日志文件路径
events {
worker_connections 1024;
}http {
log_formatdm' "$request_body" ';
upstream bk_servers_2 {
server 127.0.0.1:6699;
}server {
listen 6699;
location /post/ {
proxy_pass http://bk_servers_2/api/log/letv/env;
access_log /home/shuhao/openresty-test/logs/post.log dm;
}
location /api/log/letv/env {
return 202;
}
}
}
使用curl命令模拟post请求
curl -i-d "arg1=1&arg2=2" "http://127.0.0.1:6699/post/"
日志用打印出结果:
"arg1=1&arg2=2"
3.使用lua获取$request_body值
条件:使用openresty或者nginx编译了lua模块。
方法:
server中使用lua_need_request_body on; 或者在location lua代码块中使用 ngx.req.read_body()
注意:
1)lua代码块中必须有执行语句,否则lua不执行,无法获取request_body;
2)不要使用return 200;等命令,有return命令,lua代码不执行。
worker_processes1;
#nginx worker 数量
error_log ~/openresty-test/logs/error.log debug;
#指定错误日志文件路径
events {
worker_connections 1024;
}http {
log_formatdm'"$request_body"';
lua_need_request_body on;
server {
listen 6699;
location /post/ {
content_by_lua '
ngx.say("-------")
ngx.req.read_body()
';
access_log ~/openresty-test/logs/post.log dm;
#return 200;
}
}
}
4. 自定义变量存放request body
方法:
【nginx|nginx 获取 post body值】1)在server 块中使用set $resp_body ""; 声明变量;
2)在location使用ngx.var.resp_body = ngx.req.get_body_data() or "-"为变量赋值
worker_processes1;
#nginx worker 数量
error_log /home/shuhao/openresty-test/logs/error.log debug;
#指定错误日志文件路径
events {
worker_connections 1024;
}http {
log_formatdm' "$request_body"--"$resp_body"';
lua_need_request_body on;
server {
listen 6699;
set $resp_body "";
location /post/ {
lua_need_request_body on;
content_by_lua '
local resp_body = ngx.req.get_body_data() or "-"
ngx.var.resp_body = resp_body
';
access_log /home/shuhao/openresty-test/logs/post.log dm;
#return 200;
}
}
}
推荐阅读
- Go|Docker后端部署详解(Go+Nginx)
- 后台|NATAPP内网穿透通过nginx实现一个端口访问多个不同端口服务
- nginx-1.20.2安装使用
- NGINX 创始人 Igor Sysoev 退出 F5(20 年发展“简史”令人肃然起敬)
- Nginx|Nginx~从入门到入坑。
- nginx|Mac配置PHP环境(brew安装nginx+php)
- 使用ngx_lua构建高并发应用(2)
- svn|前瞻(Spring Boot 2.4.0 第二个里程碑版本发布)
- nginx cache踩坑
- keepalived + nginx组建高可用负载平衡Web server集群