Search code examples
nginxcachingbrowser-cache

nginx cached index.html force reload


During a server migration a new nginx configuration was missing cache conrol directives. Hence, we ended up with a cached index.html which is very bad for our SPA that is not refreshed anymore if we deploy new code. We need the index.html to not be cached.

This was our (bad) nginx config that was online some days:

server {
  listen 80;

  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
  }

  error_page   500 502 503 504  /50x.html;

  location = /50x.html {
    root   /usr/share/nginx/html;
  }

}

We fixed our config:

server {
  listen 80;

  root /usr/share/nginx/html;

  location / {
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
    add_header Cache-Control "no-store, no-cache, must-revalidate";
  }

  location ~* \.(js|jpg|jpeg|gif|png|svg|css)$ {
    add_header Cache-Control "max-age=31536000, public";
  }

  error_page   500 502 503 504  /50x.html;

  location = /50x.html {
    root   /usr/share/nginx/html;
  }

}

QUESTION

Clients that have been to our webpage within the last days cached an old index.html. How can we force their browsers to drop their cached index.html?


Solution

  • There is no way manually reset browser cache on user side (browser) while the client do not request to server for new content. In this case can be useful access to any scripts, that you SPA is download without cache. In this case you can change this script and run force reload page (but be careful - you need any flag for prevent permanent force reloading after every page loading). For example, if you have GTM on site - this can help.

    UPD: I am not js specialist, but you needed to add GTM tag on all pages like this js-script:

    function getCookie(name) {
      let matches = document.cookie.match(new RegExp(
        "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
      ));
      return matches ? decodeURIComponent(matches[1]) : undefined;
    }
    
    was_reloaded = getCookie('was_reloaded')
    alert(was_reloaded)
    if (was_reloaded != 'yes') {
            document.cookie = "was_reloaded=yes; path=/; max-age=3600;"
        location.reload();
    } }