2

I'm running a node script on my dedicated server; it is running on port 9001; the thing is that it is reacheble on any domain hosted on my server; if I have 3 domains:

www.domain1.com
www.domain2.com
www.domain3.com

the node script answers on port 9001 of each one of them:

www.domain1.com:9001
www.domain2.com:9001
www.domain3.com:9001

since this node script is used only by the website in domain1, how can I limit it to listen only on www.domain1.com:9001?

I would like in the future to setup and run a different node script for every domain, but each one of them listening on port 9001

Cereal Killer
  • 3,387
  • 10
  • 48
  • 80
  • possible duplicate of [How do I host multiple Node.js sites on the same IP/server with different domains?](http://stackoverflow.com/questions/19254583/how-do-i-host-multiple-node-js-sites-on-the-same-ip-server-with-different-domain) – SomeKittens May 15 '14 at 18:39

2 Answers2

3

Assuming you aren't using a library like express, this should work:

var http = require('http');
http.createServer(function (req, res) {
  if (req.headers.host.indexOf('www.domain1.com') !== 0) {
    return res.writeHead(403);
  }
  // Do stuff
}).listen(9001, '127.0.0.1');

You won't be able to have multiple applications running on the same port, it'll throw Error: listen EADDRINUSE. I don't know much about your use case, but some options are:

  • Have one app listening on 9001 and a switch statement checking domains.
  • Have each app listen on a different port: 9001, 9002, 9003
SomeKittens
  • 38,868
  • 19
  • 114
  • 143
1

It is not possible to have multiple node.js processes which listen for the same port but different hosts. However, you could run them on different ports and put reverse proxy like Nginx in front of it, so that it would process requests from clients and redirect to needed node.js process based on configuration. In this case client would request for the same port, but would be proxies to specific node.js process based on reverse proxy configuration.

Andrei Beziazychnyi
  • 2,897
  • 2
  • 16
  • 11