Nginx:响应处理和带缓存的反向代理



我正在将 Nginx 作为一个简单的反向代理暨缓存运行,现在我想根据收到的响应设置一些标头(正文而不是标头)。

让 Lua location_capture_by这样做看起来很简单,但似乎我无法让缓存正常工作。

初始设置是:

location / {
..
try_files $uri @upstream_server
}
location @upstream_server {
      proxy_pass "http://web_lb";
      proxy_cache small;
      proxy_cache_methods POST;
      proxy_cache_key "$request_uri|$request_body";
      client_max_body_size 500M;
      add_header X-Cached $upstream_cache_status;
      set_real_ip_from   10.86.102.0/24;
      real_ip_header      X-Forwarded-For;
      proxy_ignore_headers Set-Cookie;
      proxy_ignore_headers Cache-Control;
}

将其更改为:


location /{
 content_by_lua '
     local res = ngx.location.capture(
                "/new-location",
                { method = ngx.HTTP_POST, body = ngx.var.request_body})
     #update response body here and header etc based on content
      ngx.say(res.body)
      '; }
location new-location{
try_files $uri @upstream_server
}
location @upstream_server {
      proxy_pass "http://web_lb;"
      proxy_cache small;
      proxy_cache_methods POST;
      proxy_cache_key "$request_uri|$request_body";
      client_max_body_size 500M;
      add_header X-Cached $upstream_cache_status;
      set_real_ip_from   10.86.102.0/24;
      real_ip_header      X-Forwarded-For;
      proxy_ignore_headers Set-Cookie;
      proxy_ignore_headers Cache-Control;
}
===

===

我发现我已经丢失了所有原始标头,作为处理Proxy_Header的一部分添加了一个标头,包括upstream_cache_status标头。但是,我发现Nginx仍然为来自缓存本身的重复请求提供服务。

有什么理由会这样吗? 我也有点早入门,所以请原谅一些基本的陷阱。

实际上,location.capture 并不是为了做你做的事情而设计的,但是,如果我猜对了(你想发送浏览器发送给你的标头到子请求),你可能可以使用 ngx.ctx + set ;)

但我想说这是一种非常肮脏的笨拙方式。

最新更新