[轉帖]nginx利用request_body記錄POST body(location中用proxy_pass)

https://www.cnblogs.com/freedom-try/p/14699538.html

  

1.完整過程

1.1 在nginx.confhttp裏面添加配置如下:

http {
	...
	log_format postdata escape=json '$remote_addr - $remote_user [$time_local] "$request" 
		                        '$status $body_bytes_sent "$http_referer" '
		                        '"$http_user_agent" "$http_x_forwarded_for" "$request_body"';
	upstream bk_server {
		server 127.0.0.1:12345;
	}
	server {
		listen 12345;
		location / {
		        proxy_pass http://bk_server/test;
                        access_log /var/log/nginx/post.log postdata;
		}
		location /test {
		        return 202;
		}
	}
	...
}

檢查nginx配置語法有無錯誤

nginx -t

若無語法錯誤,則reload nginx配置,使最新的nginx配置生效

nginx -s reload

1.2 使用curl命令模擬post請求

curl -i  -d "arg1=1&arg2=2&hi=你好" "http://127.0.0.1:12345"

查看日記:

tail -n 10 /var/log/nginx/post.log

得到結果:

...省略其他參數的值...  "arg1=1&arg2=2&hi=你好"

如果nginx裝在公網服務器上,那麼請將127.0.0.1換成公網ip

2.說明

2.1 log_format配置

log_format官方文檔
log_format 語法:

log_format name [escape=default|json|none] string ...;
  • postdata: 名稱
  • escape=json: 在配置日誌格式時加上此參數可以不轉義變量內容,這裏爲了顯示POST body裏面的中文。(escape參數,到版本1.11.8纔有,escape參數的none值到1.13.10版本纔有)
  • $request_body: 只有location中用到proxy_pass,fastcgi_pass,scgi_pass命令時,該變量纔有值。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.

2.1.1

test

2.2 bk_server

bk_server是爲了使用proxy_pass而設置的。

3.顯示HTTPS裏面的POST body(可選)

如網站已使用HTTPS,那麼配置如下:

3.1 除了需要把access_log那一行註釋掉之外,步驟1中的配置不變。

3.2 其他配置如下

server {
        # Redirect all http requests to https.
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name _;
        return 301 https://$host$request_uri;
}
server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name www.your_domain your_domain;
        ...
        # Record POST body
        location /post {
                proxy_pass http://127.0.0.1:12345;
                access_log /var/log/nginx/post.log postdata; #這裏設置之後,需要把步驟1裏面的access_log那一行註釋掉
        }
        ...
}

檢查nginx配置語法有無錯誤

nginx -t

若無語法錯誤,則reload nginx配置,使最新的nginx配置生效

nginx -s reload

使用curl命令模擬post請求

curl -i  -d "arg1=1&arg2=2&hi=你好" "https://your_domain/post"

查看日記:

tail -n 10 /var/log/nginx/post.log

得到結果:

...省略其他參數的值...  "arg1=1&arg2=2&hi=你好"

參考: nginx記錄post body/payload數據

 
分類: O&M
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章