Can you define a server's locations in multiple nginx config files?

I have multiple ruby apps running on the on the same host:

~/app1
~/app2
~/app3

And I want to have nginx proxy these apps using sub-directories like:

   http://example.com/app1
   http://example.com/app2
   http://example.com/app3

I'm curious if nginx supports me being able define these locations in multiple files, so that I could keep each configuration with the app, instead of having one monolithic config file for all of the apps:

~/app1/nginx.conf
~/app2/nginx.conf
~/app3/nginx.conf

My naive attempt of defining the server with a single location directive in each of the 3 config files led to conflicting server name "example.com" on [::]:80, ignored with a configs that look like this:

upstream app1 { server 127.0.0.1:4567; }
server {
  listen      [::]:80;
  listen      80;
  servername  example.com
  location    /app1 {
     proxy_pass  http://app1;
     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "upgrade";
     proxy_set_header Host $http_host;
     proxy_set_header X-Forwarded-Proto $scheme;
     proxy_set_header X-Forwarded-For $remote_addr;
     proxy_set_header X-Forwarded-Port $server_port;
     proxy_set_header X-Request-Start $msec;
  }
}

Is there a way to organize the configs this way?


Solution 1:

You can include external configs via include:

include /path/to/config1.conf;
include /path/to/config2.conf;
include /path/to/confdir/*.conf;

server {
    server_name example.com;
    listen      [::]:80;
    listen      80;
}

And inside separate config you can use any valid code blocks:

upstream app1 {
    server 127.0.0.1:8080;
}

location /app1 {
    proxy_pass http://app1;
}

Solution 2:

I believe, you could use this configuration:

server {
    server_name example.com;
    listen      [::]:80;
    listen      80;

    include /path/to/applications/*/nginx.conf;
}

and then in each application's directory configure the redirection like this:

location    /app1 {
    proxy_pass  http://app1;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header X-Forwarded-Port $server_port;
    proxy_set_header X-Request-Start $msec;
}