为网站内容添加Expires标头

Apache 服务器添加 Expires 标头的办法:

编辑.htaccess 文件,添加以下内容,告诉浏览器要缓存哪些类型的文件。

ExpiresActive On

  # Images
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/gif "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/webp "access plus 1 year"
  ExpiresByType image/svg+xml "access plus 1 year"
  ExpiresByType image/x-icon "access plus 1 year"

  # Video
  ExpiresByType video/mp4 "access plus 1 year"
  ExpiresByType video/mpeg "access plus 1 year"

  # CSS, JavaScript
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType text/javascript "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"

  # Others
  ExpiresByType application/pdf "access plus 1 month"
  ExpiresByType application/x-shockwave-flash "access plus 1 month"

Nginx 服务器添加 Expires 标头的办法:

在网站的配置文件中添加以下内容,然后重启 nginx 服务即可。

location ~* \.(jpg'jpeg'png'gif'ico'css'js)$ {
        expires 365d; #这里d代表一天,365d代表365天
    }location ~* \.(pdf)$ {
        expires 30d;
}