Skip to content

Instantly share code, notes, and snippets.

@billywhizz
Created April 28, 2011 19:51
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save billywhizz/947170 to your computer and use it in GitHub Desktop.
Save billywhizz/947170 to your computer and use it in GitHub Desktop.
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment