america, classic car, car-2547044.jpg

Nginx Static File Cache Control

You can boost your site’s performance by letting visitors browsers know it should cache your static files. Nginx can be configured to set the “Expires” and the “max-age directive of the “Cache-Control” HTTP response headers for static files (eg. images, style sheets, javascript) it serves up to a date in the future. This allows browsers to cache the images for the amount of time specified by the Expires header. The Nginx expires directive can be placed inside http {}, server {}, location {} blocks or in an if statement inside a location {} block.

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 90d;
log_not_found off;
}

In the configuration example above, all .js, .css, .png, .jpg, .jpeg, .gif and .ico files get an Expires header with a date 90 days into the future from the browser access time. I have also set Nginx to not log 404 errors for missing images with the log_not_found setting. When I update my own sites I know when an image is missing. I don’t want to see 404 errors for images that are being sourced to on other’s sites (hot linking).

You can use the following time units:

  • ms: milliseconds
  • s: seconds
  • m: minutes
  • h: hours
  • d: days
  • w: weeks
  • M: months (30 days)
  • y: years (365 days)

One thing to keep in mind is that the Expires header only works for 200, 201, 204, 206, 301, 302, 303, 304 and 307 HTTP code responses.

Scroll to Top
foliaceous