ScaleScaleScaleScale

Tips / Nginx


How to enable Browser Cache Static Files on Nginx

This tutorial will teach you how to configure nginx to set Expires HTTP headers and max-age directive to set a cache date for your static files  (images, CSS and Javascript files). Doing this results in saving a lot of bandwidth and a fast loading website.

I will assume you already have nginx configured and working on your server. You can place this expires directive inside http {}, server {} or location {} blocks. The best way to have all your static files cached with expires header is in this way:

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

In this example, all your .gif, .jpg, .jpeg, .png,  .css, .ico and .js files are set to be cached from the next 365 days.

To apply the changes, just reload nginx:

/etc/init.d/nginx reload

Popular search terms:

  • nginx header date
  • nginx http header expires
  • nginx expires
  • nginx browser caching
profile

Esteban Borges

Linux Geek, Webperf Addict, Nginx Fan. CTO @Infranetworking

  • What if your static files are been proxied?? How do you set this header for remote files??

  • murpium

    Do not use 365d, simply use max to make it the maximum expiration date.

  • Vipin Chaudhary

    Please Correct: .(jpg should be .(jpg Otherwise you facing problem in routing.