在nginx.conf或站点配置文件中添加缓存配置:
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_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
# 添加缓存头以便调试
add_header X-Proxy-Cache $upstream_cache_status;
}
}
}
# 删除整个缓存目录
sudo rm -rf /var/cache/nginx/*
# 或者更安全的方式
sudo find /var/cache/nginx -type f -delete
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-file-path
来清理特定文件缓存。
最佳实践是为静态资源添加版本号或哈希值:
<link rel="stylesheet" href="/css/style.css?v=1.2.3">
<script src="/js/app.js?hash=abc123"></script>
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, no-transform";
access_log off;
add_header Last-Modified "";
etag off;
# 如果使用版本化资源,可以设置更长的缓存时间
if ($query_string) {
expires max;
}
}
当更新静态资源时,可以通过以下方式之一: 1. 更改文件名(如app-v2.js) 2. 添加查询参数(如app.js?v=2) 3. 使用内容哈希(如app.abc123.js)
Webpack/Gulp等构建工具可以自动添加哈希到文件名:
// webpack.config.js
output: {
filename: '[name].[contenthash].js',
chunkFilename: '[name].[contenthash].js',
}
创建部署脚本:
#!/bin/bash
# 部署新代码
rsync -avz --delete ./dist/ user@server:/var/www/html/
# 清理nginx缓存
ssh user@server "sudo find /var/cache/nginx -type f -delete"
# 重载nginx配置
ssh user@server "sudo nginx -s reload"
curl -I http://example.com/static/js/app.js
检查X-Proxy-Cache头确认缓存状态
使用浏览器开发者工具检查资源加载情况
通过以上配置和策略,您可以有效地管理Nginx缓存并确保用户能及时获取最新的静态资源。