当网站内容更新时,Nginx的缓存机制可能导致用户无法立即看到最新内容。合理配置缓存清理机制可以确保:
在Nginx配置中设置缓存时间:
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 7d;
add_header Cache-Control "public, no-transform";
}
Nginx缓存通常存储在特定目录中(如/var/cache/nginx
),可以手动删除:
sudo rm -rf /var/cache/nginx/*
sudo service nginx reload
安装并配置ngx_cache_purge
模块:
location ~ /purge(/.*) {
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
proxy_cache_purge my_cache $1$is_args$args;
}
然后通过访问http://example.com/purge/url-to-purge
来清除特定URL的缓存。
location / {
# 当文件修改时间变化时自动失效缓存
if_modified_since before;
# ...
}
proxy_cache_key "$scheme$request_method$host$request_uri$cookie_user";
location /api/purge {
internal;
proxy_cache_purge my_cache $arg_url;
}
Nginx Plus提供了更完善的API接口用于缓存管理。
如果缓存清理不生效,检查:
通过合理配置这些缓存清理机制,可以确保用户在内容更新后能够及时看到最新内容,同时保持网站的良好性能。