在Nginx中配置静态文件缓存可以显著提高网站性能,减少服务器负载。以下是详细的配置方法:
在Nginx配置文件中(通常是nginx.conf
或站点配置文件),添加以下内容:
server {
# ... 其他配置 ...
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg|eot)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
access_log off;
}
}
expires 30d; # 30天过期
可选值:
- expires max;
- 最大过期时间(10年)
- expires 30d;
- 30天
- expires 1h;
- 1小时
- expires off;
- 禁用缓存
add_header Cache-Control "public, no-transform";
public
- 允许代理服务器缓存private
- 仅允许浏览器缓存no-cache
- 每次请求必须验证no-store
- 完全不缓存no-transform
- 禁止代理修改内容must-revalidate
- 必须重新验证过期缓存access_log off;
对于静态文件,通常不需要记录访问日志。
etag on;
location ~* \.[a-f0-9]{8}\.(css|js)$ {
expires max;
add_header Cache-Control "public, immutable";
}
proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 1m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
add_header X-Proxy-Cache $upstream_cache_status;
}
}
检查配置语法:
nginx -t
重新加载配置:
nginx -s reload
使用curl验证头部:
curl -I http://yoursite.com/static/image.jpg
应看到类似以下响应头:
HTTP/1.1 200 OK
Cache-Control: public, max-age=2592000
Expires: Thu, 31 Dec 2037 23:55:55 GMT
通过合理配置静态文件缓存,可以显著提高网站性能,减少服务器负载和带宽消耗。