插件窝 干货文章 nginx expires控制页面缓存的方法

nginx expires控制页面缓存的方法

expires 缓存 Nginx 设置 49    来源:    2025-04-27

Nginx 配置页面缓存的方法

Nginx 可以通过 expires 指令来控制页面的缓存时间,这是优化网站性能的重要手段之一。以下是详细的使用方法:

基本语法

expires [time|epoch|max|off];

常用配置示例

1. 设置固定过期时间

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 30d;  # 30天
}

2. 不同时间单位的设置

expires 1h;    # 1小时
expires 30m;   # 30分钟
expires 1d;    # 1天
expires 1w;    # 1周
expires 1M;    # 1个月(30天)
expires 1y;    # 1年

3. 特殊值

expires max;     # 设置最大过期时间(10年)
expires epoch;   # 不缓存
expires off;     # 不修改Expires和Cache-Control头部

4. 根据文件类型设置

location ~* \.(css|js)$ {
    expires 1y;
    add_header Cache-Control "public";
}

location ~* \.(jpg|jpeg|png|gif|ico)$ {
    expires 7d;
    add_header Cache-Control "public";
}

location ~* \.(pdf|doc|docx|xls|xlsx|ppt|pptx)$ {
    expires 30d;
    add_header Cache-Control "public";
}

5. 动态内容不缓存

location / {
    expires off;
    add_header Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
}

注意事项

  1. expires 指令会自动添加 Cache-Control 头部
  2. 对于静态资源,建议设置较长的缓存时间
  3. 对于动态内容,建议不缓存或设置短缓存时间
  4. 修改配置后需要重新加载 Nginx 配置:nginx -s reload
  5. 可以使用 @ 语法设置基于修改时间的缓存
location ~* \.(jpg|jpeg|png|gif|ico)$ {
    expires @30d;  # 30天后过期
}

通过合理配置 expires 指令,可以显著提高网站性能,减少服务器负载,同时为用户提供更快的访问体验。