Host multiple websites using Node.js Express

Pradino picture Pradino · Jul 22, 2015 · Viewed 12.5k times · Source

I am having problems configuring two different Node.js applications with different domains. Have two directories

"/abc/" -> express-admin setup (backend) -> admin.abc.com

and

"/xyz/" -> express setup (frontend) -> abc.com

I need admin.abc.com to point to express-admin setup and abc.com to express setup. I have vhost installed and both the site listens to port 80.

Have added

app.use(vhost('abc.com', app)); // xyz/app.js file
app.use(vhost('admin.abc.com', app)); // abc/app.js file

My problems:

  • forever is installed, whenever i start both the apps, the second one is always stopped. I tried using different port for both apps but still having the same error. Individually they run without problems.

  • I think my setup is too complicated for domain forwarding. Any better suggestions? May be I have a master app.js file which I can use to route the domains to their respective apps without using the app.js of each applications.

Answer

dreamingblackcat picture dreamingblackcat · Jul 22, 2015

I am not sure how you are using the vhost. First of all with vhost approach, you need to run only one express app. Not two. Here is an example.

var express = require('express');
var vhost = require('vhost');

/*
edit /etc/hosts:

127.0.0.1       api.mydomain.local
127.0.0.1       admin.mydomain.local
*/

// require your first app here

var app1 = require("./app1");

// require your second app here

var app2 = require("./app2");

// redirect.use(function(req, res){
//   if (!module.parent) console.log(req.vhost);
//   res.redirect('http://example.com:3000/' + req.vhost[0]);
// });

// Vhost app

var appWithVhost = module.exports = express();

appWithVhost.use(vhost('api.mydomain.local', app1)); // Serves first app

appWithVhost.use(vhost('admin.mydomain.local', app2)); // Serves second app

/* istanbul ignore next */
if (!module.parent) {
  appWithVhost.listen(8000);
  console.log('Express started on port 8000');
}

You just need to run the main express app with vhost enabled using forever.