要实现Nginx代理缓存能够实时响应网站内容变化,需要合理配置缓存策略和更新机制。以下是详细的解决方案:
首先在Nginx配置中启用代理缓存:
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_pass http://backend;
# 缓存键设置
proxy_cache_key "$scheme$request_method$host$request_uri";
# 缓存有效期为10分钟
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
# 其他响应状态码不缓存
proxy_cache_valid any 0;
}
}
}
确保后端应用返回适当的Cache-Control头部:
location / {
proxy_cache my_cache;
proxy_pass http://backend;
# 优先遵循后端返回的Cache-Control头部
proxy_ignore_headers Set-Cookie;
proxy_hide_header Set-Cookie;
# 如果后端没有设置Cache-Control,则使用默认值
proxy_cache_valid 200 302 10m;
}
后端应用应返回适当的缓存控制头:
- Cache-Control: no-cache
- 每次请求都验证缓存
- Cache-Control: no-store
- 不缓存
- Cache-Control: max-age=60
- 缓存60秒
location ~ /purge(/.*) {
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
proxy_cache_purge my_cache "$scheme$request_method$host$1";
}
然后可以通过访问 http://example.com/purge/your-url
来清除特定URL的缓存。
安装ngx_cache_purge模块后:
location ~ /purge(/.*) {
proxy_cache_purge my_cache $host$1$is_args$args;
}
在URL中添加版本号或哈希值:
http://example.com/style.css?v=123456
location /update-cache {
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
content_by_lua_block {
local args = ngx.req.get_uri_args()
local url = args["url"]
if url then
ngx.location.capture("/purge"..url)
ngx.say("Purged cache for: "..url)
else
ngx.say("Missing URL parameter")
end
}
}
Nginx Plus提供了更强大的API:
location /api/ {
api write=on;
}
然后可以使用HTTP请求清除缓存:
curl -X DELETE http://nginx/api/7/http/caches/my_cache?key=http://example.com/resource
# 添加缓存状态头
add_header X-Cache-Status $upstream_cache_status;
# 日志记录缓存命中情况
log_format cache_log '$remote_addr - $upstream_cache_status [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:100m inactive=60m use_temp_path=off;
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_key "$scheme$request_method$host$request_uri$is_args$args";
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_valid any 0;
proxy_ignore_headers Set-Cookie;
proxy_hide_header Set-Cookie;
add_header X-Cache-Status $upstream_cache_status;
}
location ~ /purge(/.*) {
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
proxy_cache_purge my_cache "$scheme$GET$host$1";
}
location /update-cache {
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
content_by_lua_block {
local args = ngx.req.get_uri_args()
local url = args["url"]
if url then
local res = ngx.location.capture("/purge"..url)
ngx.say("Purged cache for: "..url)
else
ngx.say("Missing URL parameter")
end
}
}
}
}
no-cache
通过以上配置和策略,可以实现Nginx代理缓存在保证性能的同时,能够及时响应网站内容的变化。