如何使用 NGINX 反向代理缓存多部分 POST 请求

我们在 Web 服务器前面有一个 NGINX 反向代理,需要根据请求体缓存响应(关于为什么,请参见这个论坛帖子)。

问题是,即使 POST 数据相同,多部分边界每次也不同(边界是由 Web 浏览器创建的)。

下面是请求的简化示例(请注意由浏览器生成的_WebKitFormBoundaryV2BlneaIH1rGgo0w_):

POST http://my-server/some-path HTTP/1.1
Content-Length: 383
Accept: application/json
Content-Type: multipart/form-data; boundary=----
WebKitFormBoundaryV2BlneaIH1rGgo0w

------WebKitFormBoundaryV2BlneaIH1rGgo0w
Content-Disposition: form-data; name="some-key"; filename="some-pseudo-file.json"
Content-Type: application/json

{ "values": ["value1", "value2", "value3"] }
------WebKitFormBoundaryV2BlneaIH1rGgo0w--

如果对某些人有用的话,这是我们使用的 NGINX 配置的简化示例:

proxy_cache_path /path/to/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;

location /path/to/post/request {
  proxy_pass http://remote-server;
  proxy_cache my_cache;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto $scheme;
  proxy_set_header proxy_http_version 1.1;
  proxy_set_header Connection "";
  proxy_cache_lock on;
  proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
  proxy_cache_methods POST;
  proxy_cache_key "$scheme$proxy_host$uri$is_args$args|$request_body";
  proxy_cache_valid 5m;
  client_max_body_size 1500k;
  proxy_hide_header Cache-Control;
}

我已经看到了[LUA NGINX 模块](https://github.com/openresty/lua-nginx-module),它“看起来”可以工作,但我不知道如何将其用于解析请求数据以构建缓存键,并仍然传递原始请求,或者是否有一些我可以使用的“标准”NGINX。

谢谢!

点赞