Skip to content
iD-SIGN
Contact us

NGINX cache settings for PHP-generated images and static files

Setting up caching correctly for static content can noticeably improve page load speed

1 min readpublished 11/2020

For static content that never changes during its lifetime (images, CSS files with a generated unique name, etc.), it pays to also send its expiration in the headers. If the content is only generated on first access, you need to make sure that this first request is routed to the right file. That is usually the front controller of the whole application, typically index.php. This situation often occurs when generating thumbnail images, for example with LiipImagineBundle

The NGINX configuration itself is simple and can look like this, for example:

nginx
location ~* \.(jpg|jpeg|png|webp|gif|ico|css|js|woff2)$ {
    expires 365d;
    try_files $uri /index.php$is_args$args;
}

For clarity, here is what the individual parts of the configuration and the variables used mean:

  • location ~* - a directive that applies to requests matching the given regular expression. In this particular case, we set up caching for images, CSS, JS and fonts.
  • expires 365d - sets the expiration to 365 days
  • $uri - the normalized URI from the request
  • $is_args - ? (question mark) if the request contains GET parameters, otherwise an empty string
  • $args - the GET parameters themselves

All available variables are described in the ngx_http_core_module documentation.

Tags Servers, Nginx

Share LinkedIn Facebook

Need more than an article?

A few sentences about what you are dealing with are enough.