简体   繁体   中英

How to configure nginx to redirect to same app from multiple ports?

I have a node.js app and I am running nginx as a reverse proxy server. I want to access the same app through multiple ways.

Let the ip address of machine be 12.16.12.113 . Then I want the same app to be accessible through:

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

I have 2 Configuration files for nginx in sites-available directory:

file1:

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;
    }
}

file2:

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;
    }
}

The problem is that if I link both the files in sites-enabled directory, then only the app is accessible only through 12.16.12.113:3000 . If I remove file2 , then it is accessible through test.example.com .

But I want both the methods to work.

Edit 1: Based on suggestion from this answer, I did the following test:

在此处输入图片说明

It appears that nginx is not listening to port 80. Why is this happening?

The are few ways to achieve that.

  1. You can make your Node app listen on 12.16.12.113:3000 instead of on localhost:3000 and then you will need nginx only for port 80.

  2. You can make your Node app listen on localhost:3000 (but only on localhost) and then proxy 12.16.12.113:3000 and port 80 by nginx.

  3. You can make your Node app listen on localhost:4000 or 0.0.0.0:4000 on any interface and use nginx to proxy requests to port 80 and 3000.

But you will not be able to make them both listen on the same port and the same interface without problems.

This is the only advice that could be given considering the fact that you didn't include any code example of how your Node app is binding to the ports, which would be the only relevant information here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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