Created
February 21, 2015 07:35
-
-
Save iwatakeshi/93dad93829259dd76588 to your computer and use it in GitHub Desktop.
@edwardhotchkiss Subdomain port for Koa.js https://github.com/edwardhotchkiss/subdomain
This file contains 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
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