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

时间:2019-10-09 19:46:33

标签: nginx nginx-location nginx-config

我正在尝试添加标头“ 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作为响应标头?

1 个答案:

答案 0 :(得分:0)

nginx不添加空标题。 $request_body为空,这就是为什么您看不到它的原因。根据{{​​3}},$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;
    }
  }
}