简体   繁体   English

多个位置的 NGINX 反向代理不起作用

[英]NGINX reverse proxy for multiple locations not working

I am trying to run two express.js APIs in an EC2 instance with the help of PM2 and reverse-proxy using NGINX.我正在尝试在 PM2 和使用 NGINX 的反向代理的帮助下在 EC2 实例中运行两个 express.js API。 Please find the NGINX config below,请在下面找到 NGINX 配置,

NGINX config for the locations位置的 NGINX 配置

My intention is to run the 2 APIs under the following routes:我的目的是在以下路线下运行 2 个 API:

  1. / to reverse proxy localhost:3000 /反向代理localhost:3000
  2. /local to reverse proxy localhost:3001 /local反向代理localhost:3001

To make things more clear, I need the URL containing /local or /local/ to proxy the API running on the port 3001 .为了让事情更清楚,我需要包含/local/local/的 URL 来代理在端口3001上运行的 API。 However, when I try to hit https://example.com/local or https://example.com/local/ , the response is received from the API running in port 3000 instead of the intended proxy.但是,当我尝试点击https://example.com/localhttps://example.com/local/ ,响应是从在端口 3000 中运行的 API 而不是预期的代理接收的。

This is the response returned when tried in the browser:这是在浏览器中尝试时返回的响应:

Safari screenshot Safari 截图

The solution needed is to successfully configure the 2 APIs to consume requests from the / aka root domain and the /local domain respectively.需要的解决方案是成功配置 2 个 API 以分别使用来自/ aka 根域和/local域的请求。 But both the requests go to the first one.但是这两个请求都转到第一个请求。

PS.附注。 I was also advised with a trick - tried switching the location positions (ie keeping the /local location block first followed by the / block) in the config file, still no luck - same behaviour.我还被告知了一个技巧 - 尝试在配置文件中切换位置位置(即首先保持/local位置块,然后是/块),但仍然没有运气 - 相同的行为。

The reverse proxy works fine redirecting the requests to the correct server, but the one running on '/local' gets requests forwarded containing '/local'.反向代理可以很好地将请求重定向到正确的服务器,但是在“/local”上运行的服务器会转发包含“/local”的请求。 So the express app present there looks for /local in the route, but i figured out that was not configured.所以那里的快递应用程序在路由中寻找 /local ,但我发现它没有配置。 So have something like this.所以有这样的事情。

app.get('/local', (req, res) => {
  res.send('Hello World2!')
})

Just make sure to add the prefix '/local' for all the routes in the express app server at '/local' from nginx只需确保为来自 nginx 的“/local”快速应用服务器中的所有路由添加前缀“/local”

And

"PS. I was also advised with a trick - tried switching the location positions (ie keeping the /local location block first followed by the / block) in the config file, still no luck - same behaviour." “PS。我还被告知了一个技巧 - 尝试在配置文件中切换位置位置(即首先保持 /local 位置块,然后是 / 块),仍然没有运气 - 相同的行为。”

The above will be the correct config because nginx will match and redirect the requests to the first applicable block.以上将是正确的配置,因为 nginx 将匹配并将请求重定向到第一个适用的块。 So if '/' stays before '/local' all the requests will be redirected to the first express app.因此,如果 '/' 保留在 '/local' 之前,则所有请求都将被重定向到第一个 express 应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM