繁体   English   中英

如何配置nginx从多个端口重定向到同一应用程序?

[英]How to configure nginx to redirect to same app from multiple ports?

我有一个node.js应用程序,并且正在将nginx作为反向代理服务器运行。 我想通过多种方式访问​​同一应用程序。

设机器的IP地址为12.16.12.113 然后,我希望可以通过以下方式访问同一应用:

  1. 12.16.12.113:3000
  2. test.example.com

我在sites-available目录中有2个nginx的配置文件:

文件1:

server {
    listen 80;

    server_name test.example.com;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

文件2:

server {
    listen 3000;

    server_name default_server;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

问题是,如果我同时链接了sites-enabled目录中的两个文件,则只能通过12.16.12.113:3000访问该应用程序。 如果我删除file2 ,则可以通过test.example.com访问它。

但是我希望这两种方法都能起作用。

编辑1:根据答案的建议,我进行了以下测试:

在此处输入图片说明

看来nginx没有监听端口80。为什么会发生这种情况?

有几种方法可以做到这一点。

  1. 您可以使Node应用程序在12.16.12.113:3000上侦听,而不是在localhost:3000上侦听,然后仅需要80端口的nginx。

  2. 您可以让Node应用程序在localhost:3000上侦听(但只能在localhost上),然后通过nginx代理12.16.12.113:3000和端口80。

  3. 您可以使Node应用程序在任何接口上的localhost:4000或0.0.0.0:4000上侦听,并使用nginx代理对端口80和3000的请求。

但是,您将无法使它们都在同一端口和同一接口上侦听而不会出现问题。

考虑到您没有包含任何有关Node app如何绑定到端口的代码示例的事实,这是可以给出的唯一建议,这将是此处唯一的相关信息。

暂无
暂无

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

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