Skip to content

Instantly share code, notes, and snippets.

@iwatakeshi
Created February 21, 2015 07:35
Show Gist options
  • Save iwatakeshi/93dad93829259dd76588 to your computer and use it in GitHub Desktop.
Save iwatakeshi/93dad93829259dd76588 to your computer and use it in GitHub Desktop.
function subdomain(options) {
// options?
options = options || {};
if (!options.base) {
throw new Error('options.base required!');
} else {
options.removeWWW = options.removeWWW || false;
options.debug = options.debug || false;
options.ignoreWWW = options.ignoreWWW || false;
options.prefix = options.prefix || 'subdomain';
};
// return middleware
return function*(next) {
// get host & protocol
var host = this.request.headers.host,
protocol = this.request.socket.encrypted ? 'https' : 'http';
// remove 'www' prefix from URL? (tacky, right?)
if (options.removeWWW === true) {
if (/^www/.test(host)) {
return this.response.redirect(protocol + '://' + host.replace(/^www\./, '') + this.request.url);
};
};
// subdomain specific middleware
if (host === options.base || host === 'localhost:8000' || (options.ignoreWWW && /^www\./.test(host))) {
// not a subdomain or ignoring www subdomain
yield next;
} else {
// test for subdomain
var matches = host.match(new RegExp('(.*)\.' + options.base));
// subdomain
if (matches && matches.length === 2) {
this.request.url = '/' + options.prefix + '/' + matches[1] + this.request.url;
yield next;
} else {
yield next;
}
};
};
};
module.exports = subdomain;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment