public
Last active

'connect's "vhost" middleware, modified to accept a generic handler function. Works well with "stack".

  • Download Gist
example.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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);
package.json
JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
{
"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": [
""
]
}
vhost.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// 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();
}
};
};

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.