1. 文檔html
在nginx中想利用$request_body命令獲取post請求的body參數,並落日誌,可是發現該變量值爲空,查看官網中對$request_body的描述以下:nginx
$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命令時,該變量纔有值。api
2.使用proxy_pass,fastcgi_pass, scgi_pass等命令獲取$request_body值curl
試了下用proxy_pass,的確能夠。配置以下:post
log_format main_post '$remote_addr\t$remote_user\t[$time_local]\t"$request"\t$status\t$bytes_sent\t' '"$http_referer"\t"$http_user_agent"\t"$http_x_forwarded_for"\t"$request_body"';
worker_processes 1; #nginx worker 數量 error_log logs/error.log; #指定錯誤日誌文件路徑 events { worker_connections 1024; } http { log_format dm ' "$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請求lua
curl -i -d "arg1=1&arg2=2" "http://127.0.0.1:6699/post/"
"arg1=1&arg2=2"
3.使用lua獲取$request_body值url
條件:使用openresty或者nginx編譯了lua模塊。spa
方法:debug
server中使用lua_need_request_body on; 或者在location lua代碼塊中使用 ngx.req.read_body()rest
注意:
1)lua代碼塊中必須有執行語句,不然lua不執行,沒法獲取request_body;
2)不要使用return 200;等命令,有return命令,lua代碼不執行。
worker_processes 4; #nginx worker 數量 error_log ~/openresty-test/logs/error.log debug; #指定錯誤日誌文件路徑 events { worker_connections 1024; } http { log_format dm '"$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; } } }
方法:
1)在server 塊中使用set $resp_body ""; 聲明變量;
2)在location使用 ngx.var.resp_body = ngx.req.get_body_data() or "-" 爲變量賦值
worker_processes 1; #nginx worker 數量 error_log /home/shuhao/openresty-test/logs/error.log debug; #指定錯誤日誌文件路徑 events { worker_connections 1024; } http { log_format dm ' "$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; } } }
效果:
(完)