How to serve multiple locations from a single root?

Alan asked:

I’m having nginx serve static files that map from uri paths to folder paths like:

www.tempuri.org/js <=> /var/www/plublic/js
www.tempuri.org/css <=> /var/www/plublic/css
www.tempuri.org/img <=> /var/www/plublic/img
www.tempuri.org/foobar <=> /var/www/plublic/foobar

In my nginx conf, the rules for this, essentially all have the same root:

location /js/ {
   root /var/www/public/;
}
location /css/ {
   root /var/www/public/;
}
location /foobar/ {
   root /var/www/public/;
}
location /img/ {
   root /var/www/public/;
}

How can I write a single rule for all 4 paths?

location /(css|js|img|foobar)/ {
   root /var/www/public
}

?

My answer:


root should be placed in the server block, not in the location block. This is one of the most common nginx misconfigurations.

Making this change will also fix your issue and eliminate the need for that location block.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.