多个 Node JS Express 应用程序的 Nginx 多个位置

Jan*_*ner 3 proxy nginx node.js nginx-location

我有以下配置:

location / {
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header X-NginX-Proxy true;
  proxy_pass http://localhost:3000; # this is where our node js app runs at
  proxy_set_header Host $http_host;
  proxy_cache_bypass $http_upgrade;
  proxy_redirect off;
}
Run Code Online (Sandbox Code Playgroud)

哪个代理[SERVER_IP]/localhost:3000以便它基本上将所有内容路由到 node js 应用程序。

然后我继续编写了另一个 nodejs 应用程序,它在 port 上运行5000,而不是3000

location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-NginX-Proxy true;
      proxy_pass http://localhost:3000; # this is where our node js app runs at
      proxy_set_header Host $http_host;
      proxy_cache_bypass $http_upgrade;
      proxy_redirect off;
    }

location /testing {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-NginX-Proxy true;
      proxy_pass http://localhost:5000; # this is where our node js app runs at
      proxy_set_header Host $http_host;
      proxy_cache_bypass $http_upgrade;
      proxy_redirect off;
    }
Run Code Online (Sandbox Code Playgroud)

但是,如果我转到[SERVER_IP]/testing它,将它作为 /testing 路由到我的第一个应用程序,然后生成 Express JS 消息:“无法获取 /testing”。

我更改了顺序,重新启动了 nginx 没有问题。知道为什么它不起作用吗?我假设 nginx 是路由到 Node JS 之前的第一个实例。如果我更改端口,location / { ... }我可以获得第二个应用程序,但我希望它们彼此并行运行。

谢谢

mik*_*nik 8

您可能会发现它实际上是生成 Express JS 消息的第二个应用程序:“无法获取/测试”。

Nginx proxy_pass 指令的行为因您定义它们的方式可能看起来非常微小的差异而有所不同。如果您指定一个位置块并将其 proxy_pass 到一个没有定义路径的服务器,那么整个客户端请求 uri 将被传递到上游服务器。

http://localhost/testing将代理到http://localhost:5000/testing

但是,如果您指定了附加任何内容的 proxy_pass 指令,Nginx 将替换与位置块匹配的客户端请求部分,并使用您附加到您的 proxy_pass 指令的路径。

所以这个,最后只加一个斜杠:

location /testing/ {
    proxy_pass http://localhost:5000/;
Run Code Online (Sandbox Code Playgroud)

现在导致 Nginx 这样做:

http://localhost/testing -> http://localhost:5000/

和这个:

location /testing/ {
    proxy_pass http://localhost:5000/foo/;
Run Code Online (Sandbox Code Playgroud)

会这样做:

http://localhost/testing/bar/ -> http://localhost:5000/foo/bar/

总之,proxy_pass 到裸服务器:ip 传递整个客户端请求 uri,添加一个斜杠以删除部分 uri,或添加其他内容来替代。

另一个表明它是由您的位置块的顺序引起的答案是不正确的,对回答的人给予应有的尊重,我建议您阅读他们发布的链接中的信息,但不要遵循他们的建议,因为他们似乎对Nginx 自己选择位置块的方式。