9

How can I handle subdomains request by nodejs?

for example the following code echo test in console for any request on http://localhost:9876/[anything] :

var http = require('http');

http.createServer(function(req, res){
    console.log("test");
}).listen(9876);

now I wanna answer any request on http://[anything].localhost:9876/[anything] it can be done by htaccess in apache,what is alternative in NodeJS?

Arash Milani
  • 6,149
  • 2
  • 41
  • 47
Moein Hosseini
  • 4,309
  • 15
  • 68
  • 106

1 Answers1

8

Your application is already capable of handling requests for multiple hosts.

Since you haven't specified a hostname:

[...] the server will accept connections directed to any IPv4 address (INADDR_ANY).

And, you can determine which host was used to make the request from the headers:

var host = req.headers.host; // "sub.domain:9876", etc.

Though, you'll also need to configured an IP address for the subdomains in DNS or hosts.

Or, with a services such as xip.io -- using an IP address rather than localhost:

http://127.0.0.1.xip.io:9876/
http://foo.127.0.0.1.xip.io:9876/
http://anything.127.0.0.1.xip.io:9876/
Arash Milani
  • 6,149
  • 2
  • 41
  • 47
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199