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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.