Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying a subdomain in the route definition in Express

I'm new to ExpressJS and NodeJS in general, so I need directions on how to achieve this effect:

app.get('/', 'sub1.domain.com', function(req, res) { 
    res.send("this is sub1 response!"); 
});

app.get('/', 'sub2.domain.com', function(req, res) {
    res.send("this is sub2 response!");
}

So that when I request sub1.domain.com the first handler reacts and on sub2.domain.com I get response from second handler. I've read some questions on SO about using vhost for this purpose, but I'd be more happy if what I described above worked rather than creating multiple server instances like in vhost.

like image 846
moriesta Avatar asked Sep 03 '13 18:09

moriesta


People also ask

What is sub domain routing?

Typically, to route traffic for a subdomain, you create a record in the hosted zone that has the same name as the domain. For example, to route internet traffic for acme.example.com to a web server in your data center, you create a record named acme.example.com in the example.com hosted zone.

What is a subdomain according to DNS?

A subdomain is a domain that is a part of a larger domain under the Domain Name System (DNS) hierarchy. It is used as an easy way to create a more memorable Web address for specific or unique content with a website.


1 Answers

A quick and simple solution is:

app.get('/', function(req, res) {

  var hostname = req.headers.host.split(":")[0];

  if(hostname == "sub1.domain.com")
    res.send("this is sub1 response!");
  else if(hostname == "sub2.domain.com")
    res.send("this is sub2 response!");

});

Reference:

http://code4node.com/snippet/http-proxy-with-custom-routing

like image 199
Jazor Avatar answered Sep 21 '22 10:09

Jazor