如何在nginx中添加请求正文的内容作为响应头?



我正在尝试添加一个标头"X-Body"并将其设置为nginx conf中请求的响应正文。

pid logs/nginx.pid.test;
error_log logs/error.log.test debug;
worker_rlimit_core 500M;
worker_processes  1;
master_process off;

events {
worker_connections  1024;
}
http {
include            mime.types;
default_type       application/json;
sendfile           on;
keepalive_timeout  65;
variables_hash_max_size 2048;
server {
listen       65311;
server_name  test;
access_log   logs/test;
location / {
echo "Nginx response";
proxy_pass_request_headers on;
default_type application/json;
echo_read_request_body;
add_header X-Body $request_body;
return 200;
}
}
}

需要以下卷曲请求的标头 X-Body。但是找不到。

curl -vk "localhost:65311" -d '{"key":"value"}' -H "Content-Type: application/json"
* Rebuilt URL to: localhost:65311/
*   Trying ::1...
* TCP_NODELAY set
* connect to ::1 port 65311 failed: Connection refused
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 65311 (#0)
> POST / HTTP/1.1
> Host: localhost:65311
> User-Agent: curl/7.52.1
> Accept: */*
> Content-Type: application/json
> Content-Length: 15
>
* upload completely sent off: 15 out of 15 bytes
< HTTP/1.1 200 OK
< Server: Test
< Date: Wed, 09 Oct 2019 19:28:14 GMT
< Content-Type: application/json
< Content-Length: 0
< Connection: keep-alive
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact

此外,nginx是用echo模块构建的。如何将发布的 JSON 添加为响应标头?

nginx不添加空标头。$request_body是空的,这就是为什么你看不到它。根据文档,$request_body仅在特定条件下添加,特别是在代理时。

这是一个有效的配置:

http {
log_format postdata escape=json '"$request_body"';
server {
listen       65311;
server_name  test;
location /success {
return 200;
}
location / {
proxy_redirect off;
proxy_pass_request_body on;
proxy_pass $scheme://127.0.0.1:$server_port/success;
add_header X-Body $request_body;
access_log  logs/test.log postdata;
}
}
}

相关内容

最新更新