Created
July 29, 2011 12:35
-
-
Save criminy/1113730 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function url_rewrite_based_on_hostname(hostname,prefix_path){ | |
if (!hostname) throw new Error('url rewrite hostname required'); | |
if (!prefix_path) throw new Error('url rewrite prefix path required'); | |
var regexp = new RegExp('^' + hostname.replace(/[*]/g, '(.*?)') + '$'); | |
// this is the actual middleware implementation, that is called when you get an HTTP request. | |
return function fn(req, res, next){ | |
if (!req.headers.host) return next(); // skip if there is no HOST header. | |
var host = req.headers.host.split(':')[0]; // get the HOST header | |
if (req.subdomains = regexp.exec(host)) { // see if the hostname matches, and pull out subdomains. | |
req.url = prefix_path + req.url; // REWRITE THE URL | |
req.subdomains = req.subdomains.slice(1); // GET SUBDOMAINS (probably USELESS) | |
}; | |
next(); // Delegate to next middleware | |
}; | |
}; | |
domain1.com => 127.0.0.1:9000/path1 | |
domain2.com => 127.0.0.1:9000/path2 | |
domain3.com => 127.0.0.1:9000/path3 | |
var express = require('express'); | |
var app = express.createServer( | |
url_rewrite_based_on_hostname("domain1.com","/path1"), | |
url_rewrite_based_on_hostname("domain2.com","/path2"), | |
url_rewrite_based_on_hostname("domain2.com","/path3"), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment