您可以在多个 nginx 配置文件中定义服务器的位置吗?

aub*_*des 16 nginx

我在同一主机上运行了多个 ruby​​ 应用程序:

~/app1
~/app2
~/app3
Run Code Online (Sandbox Code Playgroud)

我想让 nginx 使用子目录代理这些应用程序,例如:

   http://example.com/app1
   http://example.com/app2
   http://example.com/app3
Run Code Online (Sandbox Code Playgroud)

我很好奇 nginx 是否支持我在多个文件中定义这些位置,以便我可以将每个配置保留在应用程序中,而不是为所有应用程序拥有一个单一的配置文件:

~/app1/nginx.conf
~/app2/nginx.conf
~/app3/nginx.conf
Run Code Online (Sandbox Code Playgroud)

我在 3 个配置文件中的每一个中都使用单个位置指令定义服务器的天真尝试导致conflicting server name "example.com" on [::]:80, ignored配置如下所示:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法以这种方式组织配置?

Ale*_*kin 13

我相信,你可以使用这个配置:

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

    include /path/to/applications/*/nginx.conf;
}
Run Code Online (Sandbox Code Playgroud)

然后在每个应用程序的目录中像这样配置重定向:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 缺点是您不能在“server”块中定义多个上游,但我认为这个答案很好地服务了 OP 的用例。 (2认同)

Sle*_*huk 8

您可以通过 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;
}
Run Code Online (Sandbox Code Playgroud)

在单独的配置中,您可以使用任何有效的代码块:

upstream app1 {
    server 127.0.0.1:8080;
}

location /app1 {
    proxy_pass http://app1;
}
Run Code Online (Sandbox Code Playgroud)

  • 看起来在 server 块之外不允许 location 指令。至少对我来说,nginx 报告“此处不允许使用”指令。 (6认同)
  • 这真的有效吗?上游模块不需要在服务器模块块之外吗? (5认同)
  • 这个答案是错误的 (2认同)