nginx 代理忽略并删除上游“缓存控制”标头

问题描述 投票:0回答:1

我在两台单独的机器上设置了 nginx 后端和代理,并且在代理服务器上启用了缓存,我的问题是代理没有收到某些请求的“Cache-Control”标头,并且不缓存响应.

奇怪的是,它对于图像、CSS、JS...可以按预期工作,但对于 php 和 html 则不然。

我测试了直接使用curl从后端获取一个简单的html页面:

curl --resolve example.com:443:<backend ip> https://example.com/test.html -I
HTTP/2 200 
server: nginx
date: Mon, 05 Feb 2024 03:41:10 GMT
content-type: text/html; charset=utf-8
content-length: 2
last-modified: Mon, 05 Feb 2024 02:37:05 GMT
etag: "65c049d1-2"
expires: Wed, 15 May 2024 03:41:10 GMT
cache-control: max-age=8640000
accept-ranges: bytes

并从代理获取它:

curl https://example.com/test.html -I -k
HTTP/2 200 
server: nginx
date: Mon, 05 Feb 2024 03:43:09 GMT
content-type: text/html; charset=utf-8
content-length: 2
last-modified: Mon, 05 Feb 2024 02:37:05 GMT
etag: "65c049d1-2"
x-cache-status: MISS
x-cache-date: Mon, 05 Feb 2024 03:43:09 GMT
accept-ranges: bytes

从代理获取 png 文件:

curl https://example.com/test.png -I
HTTP/2 200 
server: nginx
date: Mon, 05 Feb 2024 04:40:04 GMT
content-type: image/png
content-length: 2727
last-modified: Fri, 23 Apr 2021 18:03:03 GMT
etag: "60830bd7-aa7"
expires: Wed, 06 Mar 2024 04:40:01 GMT
cache-control: max-age=2592000
x-cache-status: HIT
x-cache-date: Mon, 05 Feb 2024 04:40:01 GMT
accept-ranges: bytes

在我的后端配置中,我使用服务器块中的

add_header Cache-Control "max-age=43200";
指令设置缓存控制标头,而没有任何其他
add_header
指令。我的代理配置是:

location / {
        proxy_pass https://<backend_ip>;
        proxy_ssl_name example.com;
        proxy_set_header X-Real-IP       $remote_addr;
        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_cache CACHE;
        proxy_ignore_headers Expires Set-Cookie Vary;       
        add_header X-Cache-Status $upstream_cache_status;
        add_header X-Cache-Date $upstream_http_date;
}
nginx caching proxy
1个回答
0
投票

检查缓存密钥:

proxy_cache_key "$scheme$request_method$host$request_uri";

记录和调试:

error_log /var/log/nginx/error.log debug;

检查响应标头:

curl --resolve example.com:443:<backend ip> https://example.com/test.php -I

绕过代理进行测试:

location /test.html {
    proxy_pass https://<backend_ip>;
    proxy_ssl_name example.com;
    proxy_set_header X-Real-IP       $remote_addr;
    proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_ignore_headers Expires Set-Cookie Vary;       
    add_header X-Cache-Status $upstream_cache_status;
    add_header X-Cache-Date $upstream_http_date;
    proxy_cache CACHE;
    proxy_cache_bypass $http_upgrade;
    proxy_no_cache $http_upgrade;
}

location / {
    try_files $uri $uri/ /index.php?$args;
}
© www.soinside.com 2019 - 2024. All rights reserved.