igielski.dev

How to prevent caching JS and CSS files in Magento 2

21 April 2016

If you’re using nginx on local environment, you are probably also copy-pasted nginx.conf.sample provided by Magento as your configuration.

Unfortunately, this config contains something that might make you crazy. CSS, JS and almost every other file from pub/static might not be updated after page reload, because their expiration date was set to one year.

Let’s fix it!

  1. Find out where are your nginx configuration files are stored, then open file with Magento 2 configuration, in my case it’s /usr/local/etc/nginx/magento2.conf, then find out this section:
location ~* .(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2)$ {
    add_header Cache-Control "public";
    add_header X-Frame-Options "SAMEORIGIN";
    expires +1y;
  1. By default, ico, jpg, jpeg... files from pub /static expire after one year.

We need to add a condition to disable caching in developer mode:

location ~* .(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2)$ {
    add_header Cache-Control "public";
    add_header X-Frame-Options "SAMEORIGIN";

    if ($MAGE_MODE = "developer") {
        expires off;
    }
    if ($MAGE_MODE != "developer") {
        expires +1y;
    }
  1. Reload Nginx, for example using sudo nginx -s reload and enjoy no caching!