billywhizz
4/28/2011 - 7:51 PM

Example of vhosts in node.js

Example of vhosts in node.js

var http = require("http");

/*
add following to your hosts config to test:

10.11.12.8 www.vhost1.net
10.11.12.8 www.vhost2.com
10.11.12.8 www.vhost3.test.com
10.11.12.8 static.vhost1.net

were the IP is the IP of the machine this is running on

*/

http.createServer(function(req, res) {
	if(!req.headers.host) {
		// serve default 404 for server if no host specified
		res.writeHead(404);
		res.end();
	}
	else {
		// we have a host header. let's parse it and see which host we need to serve
		var hostname = req.headers.host.split(":")[0]
		switch(hostname) {
			case "www.vhost1.net":
				res.writeHead(200);
				res.end("<html><body><p>Served from " + hostname + "</p></body></html>");
				break;
			case "www.vhost2.com":
				res.writeHead(200);
				res.end("<html><body><p>Served from " + hostname + "</p></body></html>");
				break;
			case "www.vhost3.test.com":
				res.writeHead(200);
				res.end("<html><body><p>Served from " + hostname + "</p></body></html>");
				break;
			case "static.vhost1.net":
				res.writeHead(200);
				res.end("<html><body><p>Served from " + hostname + "</p></body></html>");
				break;
			default:
				// we don't know the host so return a 404
				res.writeHead(404);
				res.end();
				break;
		}
	}
}).listen(8000);