How to set up multiple subdomains in Express.js or Connect.js

I'm used to working with httpd (Apache), which provides a way to configure subdomains mapped to a directory. How can I do the same in Connect.js / Express.js? I see that the only thing I have is routes that I'm not sure how I can use to configure subdomains. I have subdomains like m.mysite.com, sync.mysite.com

Can anyone help?

+51
subdomain express
Apr 26 2018-11-11T00:
source share
5 answers

Or, alternatively, you can use vhost .

Then create several sites in your own directory and export the express application, for example. /path/to/m/index.js :

 var app = express() /* whatever configuration code */ exports.app = app // There is no need for .listen() 

Then process all the requests in the following application:

 var vhost = require('vhost'); express() .use(vhost('m.mysite.com', require('/path/to/m').app)) .use(vhost('sync.mysite.com', require('/path/to/sync').app)) .listen(80) 

Note that /path/to/m and /path/to/sync can be absolute paths (as mentioned above) or relative paths.

+113
Apr 26 '11 at 15:09
source share

You can add a subdomain to the request and then check it in subsequent calls to next() .

I got the following code from> http://groups.google.com/group/express-js/browse_thread/thread/b04bbaea7f0e8eed (so full credit to the original author)

 app.get('*', function(req, res, next){ if(req.headers.host == 'some.sub.domain.com') //if it a sub-domain req.url = '/mysubdomain' + req.url; //append some text yourself next(); }); // This will mean that all get requests that come from the subdomain will get // /subdomain appended to them, so then you can have routes like this app.get('/blogposts', function(){ // for non-subdomain }); app.get('/mysubdomain/blogposts', function(){ // for subdomain }); 
+18
Apr 26 '11 at 14:25
source share

I recently ran into this problem and wrote a module to help with it using express 4. https://www.npmjs.org/package/express-subdomain .

An example is the api subdomain.

 var express = require('express'); var app = express(); var router = express.Router(); //api specific routes router.get('/', function(req, res) { res.send('Welcome to our API!'); }); router.get('/users', function(req, res) { res.json([ { name: "Brian" } ]); }); app.use(subdomain('api', router)); app.listen(3000); 

Check out the module on npm to see more examples.

+13
Apr 27 '14 at 15:06
source share

I created a module to help with subdomains in Express: https://github.com/WilsonPage/express-subdomain-handler

+6
Jan 29 '12 at 19:14
source share

try this template

https://github.com/sabasm/express-vhost

I made a domain and subdomain working for another SO answer

0
Apr 17 '19 at 18:22
source share



All Articles