Nginx reverse proxy in nested locations

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.

Related:


Leave a Reply