Skip to content

Instantly share code, notes, and snippets.

@TooTallNate
Created February 10, 2011 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TooTallNate/820042 to your computer and use it in GitHub Desktop.
Save TooTallNate/820042 to your computer and use it in GitHub Desktop.
'connect's "vhost" middleware, modified to accept a generic handler function. Works well with "stack".
var vhost = require('vhost');
var stack = require('stack');
var foo = function(req, res) {
// Do something...
}
var bar = function(req, res) {
// Do something else...
}
var handler = stack(
// Only for top-level 'foo.com'
vhost('foo.com', foo),
// For all subdomains at 'bar.com'
vhost('*.bar.com', bar)
);
var server = require('http').createServer(handler);
{
"name": "vhost",
"description": "'connect's \"vhost\" middleware, modified to accept a generic handler function. Works well with \"stack\", \"connect\", and \"http\" servers.",
"tags": [
"vhost",
"connect",
"stack",
"http",
"server"
],
"version": "0.0.2",
"repository": {
"type": "git",
"url": "git://gist.github.com/820042.git"
},
"homepage": "https://gist.github.com/820042",
"author": "Nathan Rajlich <nathan@tootallnate.net>",
"main": "./vhost.js",
"engines": {
"node": "*"
},
"directories": {},
"files": [
""
]
}
// Modified from "connect" to work nicely with "stack", "connect" or the regular "http" server.
// Pass a regular 'handler' function instead of a 'server' instance.
module.exports = function vhost(hostname, handler){
var regexp = new RegExp('^' + hostname.replace(/\./g, '\\.').replace(/[*]/g, '(.*?)') + '$');
return function vhost(req, res, next){
// In the case of a regular 'http.Server', there will be no 'next', so define one just in case
next = next || function() { res.writeHead(404); res.end("Not Found"); };
// An HTTP/1.0 request won't have a 'Host' header...
if (!req.headers.host) return next();
var host = req.headers.host.split(':')[0];
if (req.subdomains = regexp.exec(host)) {
req.subdomains = req.subdomains.slice(1);
handler.call(this, req, res, next);
} else {
next();
}
};
};
@coolaj86
Copy link

fyi, this should be updated with some bugfixes from connect-vhost - notably that the regex should be case-insensitive

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment