如何通过后端的 ETag/Last-Modified 字段更新 Nginx 反向代理缓存?

uky*_*ang 3 nginx reverse-proxy

我正在尝试让我的 Nginx 反向代理正常工作。但是,我发现一旦文件被缓存,即使后端文件发生更改,它也永远不会更新/重新验证,这可以通过ETagorLAST-Modified字段来识别。有人可以帮我解决这个问题吗?

这是我的设置:

proxy: proxy.test.com
backend: back.example.com
Run Code Online (Sandbox Code Playgroud)

nginx 设置:

proxy_cache_path /home/cache levels=1:2 keys_zone=cache_rev:16m inactive=14d max_size=12g;
proxy_cache_key "$scheme://$host$request_uri";
server {
    listen 80 default_server;

    resolver 74.82.42.42;
    server_name proxy.test.com;

    location ~ ^/ {
        proxy_pass http://back.example.com$request_uri;
        proxy_redirect off;
        proxy_buffering on;
        proxy_cache_revalidate on;
        proxy_pass_header Set-Cookie;

        proxy_cache cache_rev;
        proxy_cache_use_stale  error timeout invalid_header updating http_500 http_502 http_503 http_504;
        proxy_cache_valid 200  1d;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        add_header X-Cache-Status $upstream_cache_status;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是更改的curl信息beforeafter后端文件。

更改前index.html

$ curl -I http://proxy.test.com/index.html
HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Sat, 12 Dec 2015 14:30:18 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 18283
Connection: keep-alive
Last-Modified: Sat, 12 Dec 2015 14:09:14 GMT
ETag: "261e044-476b-526b3fc1b6983"
Content-Language: zh-TW
X-Cache-Status: HIT
Accept-Ranges: bytes

$ curl -I http://back.example.com/index.html
HTTP/1.1 200 OK
Date: Sat, 12 Dec 2015 14:30:32 GMT
Server: Apache
Last-Modified: Sat, 12 Dec 2015 14:30:32 GMT
ETag: W/"261e044-476d-526b44eb57c31"
Accept-Ranges: bytes
Content-Length: 18285
Content-Type: text/html; charset=utf-8
Run Code Online (Sandbox Code Playgroud)

更改后index.html

$ curl -I ttp://proxy.test.com/index.html
HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Sat, 12 Dec 2015 14:30:54 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 18283
Connection: keep-alive
Last-Modified: Sat, 12 Dec 2015 14:09:14 GMT
ETag: "261e044-476b-526b3fc1b6983"
Content-Language: zh-TW
X-Cache-Status: HIT
Accept-Ranges: bytes

$ curl -I http://back.example.com/index.html
HTTP/1.1 200 OK
Date: Sat, 12 Dec 2015 14:30:53 GMT
Server: Apache
Last-Modified: Sat, 12 Dec 2015 14:30:53 GMT
ETag: W/"261e044-476b-526b450fe6a03"
Accept-Ranges: bytes
Content-Length: 18283
Content-Type: text/html; charset=utf-8
Run Code Online (Sandbox Code Playgroud)

Evi*_*lan 7

单独的 Etag 无法帮助您。Etag用于客户端(浏览器)的条件请求,控制自己的缓存。

如果 Nginx 在其缓存中找到资源,则不会访问上游。反向代理的目的是通过不每次都连接到上游来加快速度。您应该在上游服务器上设置Expires: DATE/TIMECache-control: max-age=XXX标头(或者最好两者都设置),让缓存知道它可以将文件缓存多长时间。对于动态内容,最好使用cache-control: no-cache.

检查这些链接以获取有关缓存如何工作的更详细说明HTTP/1.1

如果您想从缓存中显式删除某些内容,则必须实现清除机制来删除要更新的文件。