Reginna
Reginna

Reputation: 341

How to enable browser cache on nginx?

I tried to analyze web speed with PageSpeed Insights and Google told me that I need to enable cache.

So I added to my .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>

Or:

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

Or:

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

But they didn't help.


I also tried to use plesk Additional nginx directives:

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

And Chrome DevTools Network show:

Chrome DevTools Network

But PageSpeed always told "Serve static assets with an efficient cache policy".


Why PageSpeed can't get setting? Cache doesn't work? How to enable it?

Upvotes: 0

Views: 2872

Answers (2)

Photo Sky Art
Photo Sky Art

Reputation: 1

It is working for me:

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

Added In Additional nginx directives

Upvotes: 0

GrahamTheDev
GrahamTheDev

Reputation: 24905

Because your are on nginx .htaccess won't work so you need to use the 'plesk Additional nginx directives' part you showed.

The reason Google Page Speed Insights is still complaining is that you have set it to only cache for 24 hours (86400 is 1 day in seconds).

The 'efficient' part of 'efficient cache policy' is referring to caching files for at least 30 days, ideally longer to save traffic for return visitors.

Change it to:

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

as this will cache it for up to a year and remove the error message.

Upvotes: 1

Related Questions