Search code examples
nginxbrowser-cachenginx-reverse-proxynginx-config

Nginx: How to set headers for all the files under a specific folder


So Let's say I have my application where files are under

https://myapp.com/v1/assets/images/*.jpg

and

https://myapp.com/v1/assets/js/*.jpg

I would like to add a rule that would set no-cache headers to anything under /assets

I believe what I can for now do is

 location ~ .*assets/js/.*$ {
  add_header Cache-Control "public, max-age=0, no-store";
}

location ~ .*assets/images/.*$ {
  add_header Cache-Control "public, max-age=0, no-store";
}

But that seems not working plus if I have many other folders under assets, I will need to add a separate rule.

Can I group everything in a pattern so that anything under /assets/* would have that header?

Thanks


Solution

  • This can be done via map directive:

    map $uri $cache_control {
        ~/assets/(images|js)/    "no-cache, no-store, must-revalidate";
    }
    server {
        ...
        add_header Cache-Control $cache_control;
        ...
    }
    

    If your URI won't match the regex, $cache_control variable would have an empty value and nginx won't add that header to its response. However there are other nginx directives that could affect Cache-Control header, i.e. expires. If you have something like expires <value>; in your config, you can use two map blocks:

    map $uri $cache_control {
        ~/assets/(images|js)/    "no-cache, no-store, must-revalidate";
    }
    map $uri $expire {
        ~/assets/(images|js)/    off;
        default                  <value>;
    }
    server {
        ...
        expires $expire;
        add_header Cache-Control $cache_control;
        ...
    }
    

    And take a look at this answer to not be surprised with add_header directive behavior.