如何在Nginx上启用浏览器缓存?

时间:2019-12-04 06:44:11

标签: .htaccess nginx caching browser-cache pagespeed

我尝试使用PageSpeed Insights分析网络速度,而Google告诉我需要启用缓存。

所以我添加了我的.htaccess:

<IfModule mod_expires.c>
<FilesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|svg|webp|js|css|swf|gz|json)$">
ExpiresActive On
ExpiresDefault A604800
</FilesMatch>
</IfModule>

<IfModule mod_headers.c>
<FilesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|svg|webp|js|css|swf|gz|json)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
</IfModule>

或者:

<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access 14 days"
ExpiresByType text/css "access 7 days"
ExpiresByType text/html "access 2 days"
ExpiresByType image/png "access 1 month"
ExpiresByType image/gif "access 1 month"
ExpiresByType image/jpg "access 1 month"
ExpiresByType image/jpeg "access 1 month"
ExpiresByType text/x-javascript "access 1 year"
ExpiresByType application/pdf "access 1 week"
ExpiresByType image/x-icon "access 2 months"
ExpiresByType application/x-shockwave-flash "access 7 months"
</IfModule>

或者:

<IfModule mod_expires.c>
<Filesmatch "\.(jpg|jpeg|png|gif|js|css|swf|ico|woff|mp3)$">
  ExpiresActive on
  ExpiresDefault "access plus 30 days"
</Filesmatch>
</IfModule>

但是他们没有帮助。


我还尝试使用plesk其他nginx指令:

location ~* \.(?:jpg|jpeg|gif|png|webp|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc|js|css|json)$ {
  etag on;
  expires 1M;
  if_modified_since exact;
  add_header Pragma "public";
  add_header Cache-Control "public, max-age=86400,no-transform";
}

Chrome DevTools Network显示:

Chrome DevTools Network

但是PageSpeed总是告诉“ 通过有效的缓存策略提供静态资产”。


为什么无法设置PageSpeed?缓存不起作用?如何启用它?

1 个答案:

答案 0 :(得分:0)

由于您使用的是nginx .htaccess,因此无法使用,因此您需要使用显示的“ plesk Additional nginx指令”部分。

Google Page Speed Insights仍然抱怨的原因是您已将其设置为仅缓存24小时(86400是1天,以秒为单位)。

“高效缓存策略”的“高效”部分是指将文件缓存至少30天,最好是更长的时间以节省回头客的流量。

将其更改为:

add_header Cache-Control "public, max-age=31536000,no-transform";

因为它将最多缓存一年并删除错误消息。