Search code examples
nginxwebserver

how to configure cache response header for root path only?


i am using nginx for static files and want that all files should be cached by browser, but not index.html. Tried following config but i get cache response header for index.html also. how can i change config?

server{
  location = / {
   try_files $uri $uri/ =404;
  }
  location / {
   try_files $uri $uri/ =404;
   add_header 'Cache-Control' "public, max-age=3600";
  }
}

Solution

  • To understand the logic of try_files $uri $uri/ ... directive (and the whole nginx behavior) I recommend you to read this answer at ServerFault. The essential thing is

    The very important yet absolutely non-obvious thing is that an index directive being used with try_files $uri $uri/ =404 can cause an internal redirect.

    This is what happens with your current config. The $uri/ argument of the try_files directive causes nginx to make an internal redirect from / to /index.html, and that URI in turn is processed by the location / { ... }, not the location = / { ... }! To achieve what you want you can use

    location = /index.html {
        try_files $uri $uri/ =404;
    }
    location / {
        try_files $uri $uri/ =404;
        add_header 'Cache-Control' "public, max-age=3600";
    }
    

    Moreover, since the try_files $uri $uri/ =404; is default nginx behavior, you can further simplify it to

    location = /index.html {}
    location / {
        add_header 'Cache-Control' "public, max-age=3600";
    }