Prevent Nginx Regex Rule from Overriding Another Rule

configurationnginx

I have a Nginx server acting as a reverse proxy for a couple services, the config is similar to this one

location /backend/service1 {
        proxy_pass http://pathto/service1;
}

location / {
        root /a/folder
}

location ~* (\.js|\.css)$
        expires 8d;

        root /home/files/abc/bcd;
}

My problem here is that recently the service1 from backend has to serve a couple static files like /backend/service1/something/file1.js or /backend/service1/something/style.css and the second location, since it's a regex location rule, overrides the first one

All static files provided by backend/service1 have a certain prefix (something), so I tried to improve the regex from the second location to have negative lookahead/lookbehind, but it doesn't seem to work, probably because the main pattern has to have a fixed length (this is what i tried without luck)

location /backend/service1 {
        proxy_pass http://pathto/service1;
}

location / {
        root /a/folder
}

location ~* (?<!something)(.*)(\.js|\.css)$
        expires 8d;

        root /home/files/abc/bcd;
}

How can I achieve this?

Best Answer

If "something" immediately follows /backend/service1, you can add another more specific location that takes precedence over regex locations:

location /backend/service1 {
    proxy_pass http://pathto/service1;
}  
location ^~ /backend/service1/something/ {
    proxy_pass http://pathto/service1/something/;
}  
location ~* \.(js|css)$ { ... }

If the "something" is embedded anywhere in the URL, you will need to use a regular expression, possibly with the notorious negative lookahead. By trial and error, I found a working expression:

location ~* ^(?!.*something).*\.(js|css)$ { ... }