Nginx reverse proxy in nested locations

cachenginxreverse-proxystatic-content

I'm using Nginx as a reverse proxy for multiple applications in multiple servers and I'm trying to add common cache directives to static files of each application.

My original configuration is something like this:

location /app1{
    ...
    proxy_pass http://127.0.0.1:8081/app1;
}

location /app2{
    ...
    proxy_pass http://127.0.0.1:8082/app2; 
}

...

To add the static file directives I can add a nested location to each location like this:

location /app1{
    ...
    proxy_pass http://127.0.0.1:8081/app1;
    location ~* \.(css|js|ico|gif|jpg|jpeg|png)$ {
        expires 1d;
        ...
        proxy_pass http://127.0.0.1:8081;
    }
}

location /app2{
    ...
    proxy_pass http://127.0.0.1:8082/app2;
    location ~* \.(css|js|ico|gif|jpg|jpeg|png)$ {
        expires 1d;
        ...
        proxy_pass http://127.0.0.1:8082;
    }
}

Since I have something like 30 applications, I'm trying to simplify the code to something like this:

location /app1{
    ...
    proxy_pass http://127.0.0.1:8081/app1;
    include static_file_config.conf;
}

location /app2{
    ...
    proxy_pass http://127.0.0.1:8081/app2;
    include static_file_config.conf;
}

Is there a way I can simplify the code so I don't end with 30 identical locations for static files?

Please note that each application serves its own static files.

Best Answer

Perhaps instead of having many locations, you could use regex to match a particular URI to your upstream application:

location ~ /(app)(\d+) {
   proxy_pass http://127.0.0.1:808$2/$1$2;
   include static_file_config.conf;
}

You can see how it works here: https://regex101.com/r/sM3eS9/1