Improving Google Page Speed Insights Score: Setting Cache Headers in NGINX

Cache (not cash)


You may get several errors that look similar to the errors below shown on referencing "expiration not specified".

Spoiler Alert: They get 58/100 on Mobile, 75/100 on Desktop

This can be solved very quickly and easily if you have access to your server's config settings. Specifically what we are doing is setting a max age, or, expiry date cache headers for files that live on your server. From the description on PageSpeed Insights: 

Leverage browser caching

Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network.

Source: Google

If you open up your site specific NGINX config, this will need to be added to the backend server block, which will deal with php, setting these headers should be positioned above the other location blocks within the same server block:

location ~* \.(?:ico|css|js|gif|jpe?g|png|svg|woff)$ {
    expires 14d;
    add_header Pragma public;
    add_header Cache-Control "public";
    try_files $uri @rewrite;

You may have noticed that I have set these headers to expire after 14 days, Google seems to accept it as an acceptable duration, though I have not seen any suggestion of what this should be.