How to set no cache on only the index.html page in NGINX

pike picture pike · Feb 27, 2018 · Viewed 9.1k times · Source

My current project is almost working with the following configuration:

root %%COMP_WEB_ROOT;

# COMP Static File serving
location /comp {
    alias %%COMP_WEB_ROOT;
    try_files $uri$args $uri$args/ /index.html;
    add_header 'Cache-Control' 'no-cache, no-store, must-revalidate';
}

# Hide the index file, not exposing that path specifically
location = /index.html {
    internal;
}

With this, I am preventing caching for the entire application, which is not desirable, since I only want to prevent the index.html page from storing cache.

So I have tried to put the add_header line inside the second block like this:

root %%COMP_WEB_ROOT;

# COMP Static File serving
location /comp {
    alias %%COMP_WEB_ROOT;
    try_files $uri$args $uri$args/ /index.html;
    error_page 401 = @error401web;
}

# Hide the index file so that we're not exposing that path specifically
location = /index.html {
    internal;
    add_header 'Cache-Control' 'no-cache, no-store, must-revalidate';
}

NGINX is able to run, but index.html seems to still storing the cache as if the add_header isn't there.

Is there some other command I am missing?

Answer

user6188497 picture user6188497 · Feb 27, 2018

I only want to prevent the index.html page from storing cache.

  • no-cache: prevents from reusing the resource without validating it
  • no-store: prevents from storing the cache on client side

In your case I'd try this:

location = /index.html {
    internal;
    add_header Cache-Control 'no-store';
}

...and then CTRL+F5 to force refresh all resources in your browser.
From this point your index.html should work in the way you wanted.