diff --git a/lib/request.js b/lib/request.js index b1c1192077..12d8c6b963 100644 --- a/lib/request.js +++ b/lib/request.js @@ -401,18 +401,23 @@ req.__defineGetter__('auth', function(){ /** * Return subdomains as an array. * - * For example "tobi.ferrets.example.com" - * would provide `["ferrets", "tobi"]`. + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. * * @return {Array} * @api public */ req.__defineGetter__('subdomains', function(){ - return this.get('Host') - .split('.') - .slice(0, -2) - .reverse(); + var offset = this.app.get('subdomain offset'); + if (offset == null) offset = 2; + + return this.get('Host').split('.').reverse().slice(offset); }); /** diff --git a/test/req.subdomains.js b/test/req.subdomains.js index 0447575e49..befafeb22f 100644 --- a/test/req.subdomains.js +++ b/test/req.subdomains.js @@ -33,5 +33,55 @@ describe('req', function(){ .expect('[]', done); }) }) + + describe('when subdomain offset is set', function(){ + describe('when subdomain offset is zero', function(){ + it('should return an array with the whole domain', function(done){ + var app = express(); + app.set('subdomain offset', 0); + + app.use(function(req, res){ + res.send(req.subdomains); + }); + + request(app) + .get('/') + .set('Host', 'tobi.ferrets.sub.example.com') + .expect('["com","example","sub","ferrets","tobi"]', done); + }) + }) + + describe('when present', function(){ + it('should return an array', function(done){ + var app = express(); + app.set('subdomain offset', 3); + + app.use(function(req, res){ + res.send(req.subdomains); + }); + + request(app) + .get('/') + .set('Host', 'tobi.ferrets.sub.example.com') + .expect('["ferrets","tobi"]', done); + }) + }) + + describe('otherwise', function(){ + it('should return an empty array', function(done){ + var app = express(); + app.set('subdomain offset', 3); + + app.use(function(req, res){ + res.send(req.subdomains); + }); + + request(app) + .get('/') + .set('Host', 'sub.example.com') + .expect('[]', done); + }) + }) + }) }) })