Nginx location fall through and matching

nginx

I've got something like the following:

server {
    server_name my.com;

    location /media/ {
       alias /home/my/media/;
       expires 1h;
    }

    location / {
        include fastcgi_params;
    }
}

I'd like to add a second /media/ location block that catches just css and js files and sets expires to max.

Ideally I'd like to also process the existing /media/ block. i.e. I just want to override expires but also process any directives in the main block.

Best Answer

Using a nested location will allow you to do what you want: Also, when the location matches the suffix of your alias directive, it's more efficient to just use root:

location /media/ {
  root /home/my;
  expires 1h;

  location ~ \.(css|js)$ {
    expires max;
  }
}

If the real config doesn't have the matching /media/, you can change that back to an alias. This approach also has the advantage of not trying to match the regex for every request, only for those that start with /media/.

Related Topic