How to set Cache-Control for images?

All the images served by Grav have “Cache-Control: no-cache” on them. This gives us a bad performance rating. The configuration documentation suggests you could set the cache_control setting, but I’ve tried cache_control: 'private, max-age=31536000' but that doesn’t do anything. I actually doubt if that is still a valid configuration parameter, since it was not included by default in my system.yaml.

How do I set the cache control instructions correctly? And should I do that in Grav at all or in Nginx?

Thanks,

Pascal

In my system.yaml there is a section for this:

    images:
  default_image_quality: 85
  cache_all: true
  cache_perms: '0755'
  debug: true
  auto_fix_orientation: true

Is it in yours?

Yes, it is, but that does not affect cache-control settings. In addition, cache-control settings do not only apply to images, but also to other assets, like JS and CSS files. So there should be a way to cover this as well. It’s unfortunate and strange that this isn’t documented anywhere, since this is very important for performance and performance rankings.

I’ve decided to try and see if NGINX could be used to set the proper cache-control. I ran into this sample NGINX config file and used the rules for assets, images and fonts to add cache-control headers to the responses. That works! I still would like to know if this is the preferred way of doing this with Grav (and NGINX). And if so, I think it would be very valuable is this was added to the documentation somewhere.

same here. Lighthouse Report says: “Serve static assets with an efficient cache policy”. Same settings in grav like plind and webfed, no change. Images and .js files are affected. Thx4help

Jup, it seems like, Grav does only apply the cache control to the pages, but not media files and or assets. It would be really great, if Grav would support that!

@manfredsteger, @NEA , I’m not that well versed on infrastructural matters, but as far as I know, and correct me if I’m wrong:

  • Grav only serves pages and can therefor set appropriate cache-control headers in the response.
  • Grav doesn’t do anything to serve images and assets (.js, .css).
    These are served by the webserver, no interference from Grav. Hence Grav cannot add any cache-control settings to the headers.
  • cache-control for images and assets should therefor be set in .htaccess, for example:
    # One year for image files
    <filesMatch ".(jpg|jpeg|png|gif|ico)$">
       Header set Cache-Control "max-age=31536000, public"
    </filesMatch>
    # One month for css and js
    <filesMatch ".(css|js)$">
       Header set Cache-Control "max-age=2678400, public"
    </filesMatch>
    
    Lighthouse will report it is happy wrt. the cache policy of static assets…

Some documents on this topic I like:

Any improvement/corrections on my thinking is welcome!

3 Likes