插件窝 干货文章 怎么在nginx中配置缓存静态文件

怎么在nginx中配置缓存静态文件

缓存 配置 Cache Nginx 992    来源:    2025-04-21

在Nginx中配置静态文件缓存

在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;
    }
}

详细配置说明

1. 设置过期时间

expires 30d;  # 30天过期

可选值: - expires max; - 最大过期时间(10年) - expires 30d; - 30天 - expires 1h; - 1小时 - expires off; - 禁用缓存

2. 缓存控制头

add_header Cache-Control "public, no-transform";
  • public - 允许代理服务器缓存
  • private - 仅允许浏览器缓存
  • no-cache - 每次请求必须验证
  • no-store - 完全不缓存
  • no-transform - 禁止代理修改内容
  • must-revalidate - 必须重新验证过期缓存

3. 禁用访问日志(可选)

access_log off;

对于静态文件,通常不需要记录访问日志。

高级缓存配置

1. 使用ETag

etag on;

2. 文件指纹缓存(适合带hash的文件名)

location ~* \.[a-f0-9]{8}\.(css|js)$ {
    expires max;
    add_header Cache-Control "public, immutable";
}

3. 代理缓存(适用于反向代理场景)

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;
    }
}

验证配置

  1. 检查配置语法:

    nginx -t
    
  2. 重新加载配置:

    nginx -s reload
    
  3. 使用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

注意事项

  1. 对于频繁更新的文件,设置较短的缓存时间
  2. 对于版本化文件(如带hash的文件名),可以设置长期缓存
  3. 开发环境可能需要禁用缓存
  4. 确保缓存不会导致用户看到过期的内容

通过合理配置静态文件缓存,可以显著提高网站性能,减少服务器负载和带宽消耗。