0

Is it possible to DRY a bunch of location blocks in Nginx with the exact same configuration, just different routes? Take a look at the following snippet off my Nginx .conf, for instance:

location / {
    proxy_pass http://127.0.0.1:3000;
    charset UTF-8;
    proxy_http_version 1.1;
  }
  location ~ /android-chrome-192x192.png {
    proxy_pass http://127.0.0.1:3000/static/brand/favicons/android-chrome-192x192.png;
    expires 365d;
    add_header Pragma public;
    add_header Cache-Control "public";
  }
  location = /android-chrome-512x512.png {
    proxy_pass http://127.0.0.1:3000/static/brand/favicons/android-chrome-512x512.png;
    expires 365d;
    add_header Pragma public;
    add_header Cache-Control "public";
  }
  location ~* \.(?:ico|svg|woff|woff2|ttf|otf|css|js|gif|jpe?g|png)$ {
   proxy_pass http://127.0.0.1:3000;
   expires 365d;
   add_header Pragma public;
   add_header Cache-Control "public";
  }

Here, I have at least two location blocks with the same values for expires, add_header Pragma, and add_header Cache-Control. In reality, I have at least 12-15 such blocks for various static files.

Is there any way to reduce the amount of redundant code here? Say, having a single block with those values and referencing that single block in each location block? I even tried using regex to just reduce the number of location blocks themselves, but that threw the following error:

"proxy_pass" cannot have URI part in location given by regular expression, or inside named location

Any workaround?

TheLearner
  • 157
  • 1
  • 6

1 Answers1

2

Try this:

location ^~ /android-chrome- {
    proxy_pass http://127.0.0.1:3000/static/brand/favicons/android-chrome-;
    expires 365d;
    add_header Pragma public;
    add_header Cache-Control "public";
}
Alexey Ten
  • 8,435
  • 1
  • 34
  • 36