Expire assets cache in browsers when replacing fingerprinted files server via nginx
<p>I'm serving a single page JavaScript application via nginx and when I deploy new version, I want to force browsers to invalidate their JS cache and request/use the newest version available.</p>

<p>So for example when I replace a file on the server's folder, named <code>my-app-8e8faf9.js</code>, with a file named <code>my-app-eaea342.js</code>, I don't want browsers to pull <code>my-app-8e8faf9.js</code> from their cache anymore. But when there is no new version available, then I still want them to read the assets from cache.</p>

<p>How do I achieve this with the nginx config? This is my existing config:</p>

<pre><code>server {
  listen 80;

  server_name my.server.com;

  root /u/apps/my_client_production/current;
  index index.html;

  # ~2 seconds is often enough for most folks to parse HTML/CSS and
  # retrieve needed images/icons/frames, connections are cheap in
  # nginx so increasing this is generally safe...
  keepalive_timeout 10;
  client_max_body_size 100M;

  access_log /u/apps/my_client_production/shared/log/nginx.access.log;
  error_log /u/apps/my_client_production/shared/log/nginx.error.log info;

  location / {
    try_files $uri $uri/ =404;

    gzip_static on;
    expires max;
    add_header  Cache-Control public;

  }

  # Error pages
  error_page 500 502 503 504 /500.html;
}
</code></pre>