Nginx:响应处理和带缓存的反向代理
qlqwjy
阅读:152
2025-06-02 22:19:02
评论:0
我正在运行 Nginx 作为一个简单的反向代理和缓存,现在我想根据收到的响应设置一些 header (正文不是 header )。
让 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;
}
======
我发现我丢失了所有原始 header ,一个 header 作为 Proxy_Header 处理的一部分添加,包括 upstream_cache_status header 。但是我发现 Nginx 仍然服务于来自缓存本身的重复请求。
有什么理由会这样吗?我也是这里的早期初学者,所以请原谅一些基本的问题。
请您参考如下方法:
实际上,location.capture 并不是为了做你所做的事情,但是,如果我理解你是正确的(你想发送浏览器发送给你的子请求的 header ),你可能可以使用 ngx.ctx + set 来破解它;)
但我会说这是一种非常肮脏的笨拙方式。
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。



