Search code examples
node.jsnode-http-proxy

Hosting two Node.JS apps on same domain


I have two node js applications I am running on the same box and I would like for it to run the first node js app for all routing except if the url is www.domain.com/blog to go to the other node js application. Is this even possible with this setup or do I have to setup subdomains and use nginx or something?


Solution

  • You can achieve this using nginx as a reverse proxy.

    Assuming you have your blog node process running on port 3000 and another node process on 3001 a simple config would look like;

    upstream blog {
       server 127.0.0.1:3000;
    }
    
    
    upstream other {
       server 127.0.0.1:3001;
    }
    
    
    server {
        listen 80;
        server_name www.domain.com;
    
        location /blog  {
            proxy_pass          http://blog;
            proxy_http_version  1.1;
            proxy_set_header    Host                $http_host;
            proxy_set_header    Upgrade             $http_upgrade;
            proxy_set_header    Connection          "Upgrade";
            proxy_set_header    X-Real-IP           $proxy_protocol_addr;
            proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
            proxy_set_header    X-Forwarded-Proto   tcp;
            proxy_set_header    X-NginX-Proxy       true;
        }
    
        location / {
            proxy_pass          http://other;
            proxy_http_version  1.1;
            proxy_set_header    Host                $http_host;
            proxy_set_header    Upgrade             $http_upgrade;
            proxy_set_header    Connection          "Upgrade";
            proxy_set_header    X-Real-IP           $proxy_protocol_addr;
            proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
            proxy_set_header    X-Forwarded-Proto   tcp;
            proxy_set_header    X-NginX-Proxy       true;
        }
      }