0

Answers to this question explain how to route sub domains in Node.js with Express.

I want to know how to do it without Express.

Here's my server module, which returns a server object:

module.exports.serve = function(port) {
    var server = https.createServer(options, function(req, res) {

        // Parse & process URL
        var reqInfo = url.parse(req.url, true, true), 
            path    = reqInfo.pathname;
        debug.log("Client [" +  req.connection.remoteAddress + 
                "]requesting resource: " + path);

        // Quickly handle preloaded requests
        if (preloaded[path])
            preloadReqHandler(req, res, preloaded[path], path);

        // Handle general requests
        else generalReqHandler(req, res, reqInfo);
    }).listen(port);
    return server;
};

No need to go into detail with the modules that handle the requests, I'm just interested in how to detect www.example.com and route it to example.com or vice-versa, via my server.


Just to add as much detail as possible, my goal here is to route all traffic from http://www.example.com and http://example.com and https://www.example.com and send it all to https://example.com. To do that, I think I just need to learn how to route the www sub domain, and then listen on both the http and https ports for that routing.

Community
  • 1
  • 1
  • I am not expert in this, so not writing this as an answer, but if you aren't using express, you can just check if it doesn't start with https://example.com return a 302 with https://example.com, and then all will be redirected quickly. – PiniH Nov 08 '14 at 21:08

1 Answers1

0

Since HTTP 1.1, user agents send the Host request header which specifies the domain. So you can get the domain (including the port if specified) from req.headers['host'] and apply your custom domain routing logic.

If you're talking with a HTTP 1.0 or older user agent, then just reply with "505 HTTP Version Not Supported" or serve some default content.

Rob W
  • 341,306
  • 83
  • 791
  • 678