Dispatch HTTP request to a handler depending on hostname
Make your HTTP server hostname-aware very simply.
You define the handler for each server name, and that will return the final handler to be passed to your HTTP server.
Works fine with Express.
npm install virtualhost
var virtualhost = require'virtualhost';var server = httpcreateServervirtualhostservers catchAll;
serversis a hash of server's configuration, each one having following options:
patterncan be a string (hostnames will simply be compared for equality), or a regular expression (you could use
/^hello\.(fr|com)$/ifor example to use this handler for
/\.domain.tld$/to match all subdomains of
domain.tld). Think about anchors (
$) when using regular expression as pattern.
function (req, res). Request matching pattern will simply be forwarded to this handler.
with_portwill include the port in the comparison. Default comparison ignores it, which means
pattern: "domain.tld" will matchdomain.tld:8080
anddomain.tld:3000` the same way. If you enable this option, you have to include port in your pattern.
catchAllis the default handler used when no server matched hostname. It's not mandatory, and defaults to a simple 404.
servers can also be a simple hash of the form
is strictly equivalent to
virtualhost"one.mydomain.tld":pattern: "one.mydomain.tld"…"two.mydomain.tld":pattern: "two.mydomain.tld"…;
Of course you can mix both syntax.
As a bonus, the
Request object will be enhanced with an additional attribute
virtualhost. You can use it in your handlers to identify context:
req.virtualhost.hostnameis the hostname without port
req.virtualhost.portis the port
req.virtualhost.matchdepends of the matching result
falseif no pattern was matched
trueif a string-pattern was matched
- an array if the matched pattern was a
matchis then the result of
String#match(), which means you can access capturing groups. If your pattern was
/mydomain\.(fr|com)/then in your handler you'll be able to access
req.virtualhost.matchwhich will contain
// Example of standard handler// This one will simply write "handler1" at "sub.domain.tld/*"var resend'handler1' ;// Example of Express 3.x app// Good guy Express now simply returns standard handler, which makes this directly usable in virtualhost :)// This one will write "handler2 (www.)" at "www.domain.tld/" and "handler2 (undefined)" at "domain.tld/"var handler2 = expressget'/' resend'handler2 (' + reqvirtualhostmatch1 + ')' ;// Example of virtualhost configurationvar apps =// Shortcut hostname→handlersubdomaintld: handler1// Full config with RegExp patternexpress: pattern: /^?domain\.tld$/ handler: handler2;httpcreateServervirtualhostappslisten;