Percy  Teng Percy Teng - 6 months ago 16
Node.js Question

how to make two different domains on the same server point to two different port by default

I used Nginx to create server block on my VPS. So now I can access both myname.com and myname.me. The problem is I am using both php and node.js on my server. So I want that when I enter myname.com as url it uses port 80 by default and when I type myname.me it directs to port 3000 which is used by my node server instead of typing myname.me:3000.

Please let me know if my description isn't clear!

Thank you!

Answer

You should be using Nginx Reverse Proxy

For your use case, just change your server blocks to be like this

server {
        listen  80;
        server_name     myname.com;
        location / {
                proxy_set_header        Host $host;
                proxy_set_header        X-Real-IP $remote_addr;
                proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header        X-Forwarded-Proto $scheme;

                proxy_pass      http://localhost:80;
                proxy_read_timeout      90;
                proxy_redirect  http://localhost:80;
        }
}

server {
        listen  80;
        server_name     myname.me;
        location / {
                proxy_set_header        Host $host;
                proxy_set_header        X-Real-IP $remote_addr;
                proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header        X-Forwarded-Proto $scheme;

                proxy_pass      http://localhost:3000;
                proxy_read_timeout      90;
                proxy_redirect  http://localhost:3000;
        }
}