如何在 proxy_pass 后将响应头从 Nginx 中删除并保存其值

基本上,我在尝试在 Nginx 中找到在 proxy_pass 情况下将响应头删除并存储在变量中的方法。 proxy_hide_header 不能让我存储该值。

换句话说:

我试图访问自定义响应头,将其保存到变量中,然后将其删除,以便不会传播到客户端。该变量然后用于访问日志。 不幸的是,以下内容似乎不起作用:

http {

log_format main '$remote_addr $http_host $destination_addr [$time_local]
"$request" $status';
access_log /opt/logs/access.log main;

server {
 listen 142.133.151.129:8090 default;

##这是响应头字段的内部变量
 set $destination_addr "-";

 location / {
 proxy_pass http://my_upstream_server;

##存储响应头字段
 set $destination_addr $sent_http_x_destination;

##现在摆脱这个响应头字段
 set $sent_http_x_destination "";
  }
 }
}

我得到的 $sent_http_x_destination 是空值。

以下是 curl 请求和响应:

# curl -Ov http://142.133.151.129:8090/ao3/vod/soccer/worldcup2014/final1

< HTTP/1.1 206 Partial Content
< Server: openresty/1.9.3.1
< Date: Tue, 16 Feb 2016 22:25:32 GMT
< Content-Type: application/octet-stream
< Content-Length: 99990100
< Connection: keep-alive
< X-Destination: 142.133.151.94

有人知道如何在将其存储和用于访问日志后删除“X-Destination”吗?我得到的是带空值的“$destination_addr”。

谢谢

点赞
用户4232534
用户4232534

我不完全确定,但我认为只要你依赖该标头来记录日志,它就需要设置为标头......否则,日志将无法使用它。

话虽如此,您可以尝试 proxy_hide_header 并查看是否起作用。

2016-02-18 23:43:59
用户4611956
用户4611956

将下面翻译成中文并且保留原本的 markdown 格式,

```The only way I can see is to create a lua script that will re-implement the proxy pass using http-resty, saves the header in an nginx variable and removes it right before returning. The saved nginx variable will then be used for access logs. This is my answer. I was hoping that nginx offers a simpler way to do that.

Please let me know your comments on this answer. Thanks for all your inputs on this topic!```

我唯一能想到的方法是创建一个 Lua 脚本,使用 http-resty 重新实现代理传递,将头信息保存在一个 nginx 变量中,然后在返回前删除它。保存的 nginx 变量将用于访问日志。

这是我的答案。

我希望 nginx 提供了一个更简单的方法来解决这个问题。

请在以下评论中分享您对我的答案的看法。

感谢您在这个话题上的所有输入!

2016-02-19 16:23:44
用户1633804
用户1633804

可以使用 proxy_hide_header 来从代理返回给 NGINX 的头文件中删除头信息,详见 ngx_http_proxy_module 文档

$upstream_http_x_destination 可用于日志记录,详见 ngx_http_upstream_module 文档

您的配置重写应该像这样:

http {
  log_format main '$remote_addr $http_host $upstream_http_x_destination '
                  '[$time_local] "$request" $status';
  access_log /opt/logs/access.log main;
  server {
    listen 142.133.151.129:8090 default;
    location / {
      proxy_hide_header x_destination;
      proxy_pass http://my_upstream_server;
    }
  }
}
2018-10-11 12:09:14