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

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

看起来使用 location_capture_by Lua 就可以做到这一点,但似乎我无法很好地使缓存正常工作。

最初的设置是:

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 仍然从缓存中提供重复的请求。

为什么会这样?而且,我是一个初学者,所以请原谅一些基本错误。

点赞
用户3026050
用户3026050

实际上,location.capture 不是设计用来做你正在做的事情,但是,如果我理解你的意思正确(你想发送浏览器发送给你的标头到子请求),你可能可以使用 ngx.ctx + set() 像黑客一样解决这个问题;)

但我要说这是一种非常肮脏的方法。

2015-06-17 18:25:29