How to create dynamic subdomains for each user using node express?

旧街凉风 提交于 2019-12-03 13:27:25

问题


On signup, I want to give user his profile and application at username.example.com I have already created wild-card dns at my domain provider website.

How can I do that?


回答1:


If using Node.js with Express.js, then:

router.get('/', function (req, res) { 
    var domain = req.get('host').match(/\w+/); // e.g., host: "subdomain.website.com"
    if (domain)
       var subdomain = domain[0]; // Use "subdomain"
    ...
});



回答2:


// you can use this implementation to get subdomain dynamically
// Use below code to get your subdomain name
// get your dynamic subdomain

app.use((req, res, next) => {
  if (!req.subdomains.length || req.subdomains.slice(-1)[0] === 'www') return next();
  // otherwise we have subdomain here
  var subdomain = req.subdomains.slice(-1)[0];
  // keep it
  req.subdomain = subdomain;
  next();
});


// conditional render a page
app.get('/', (req, res) => {
  // no subdomain
  if (!req.subdomain) {
    // render home page
    // mydomain.com
    res.render('home');
  } else {
    // render subdomain specific page
    // mypage.mydomain.com
    res.render('mypage');
  } // you can extend this else logic to render the different subdomain specific page
});


> Note: to test this locally. you can use Nginx reverse proxy to forward your test url req to your local server and do not forget to point your test url to your local host 127.0.0.1 in your hosts file of your machine


来源:https://stackoverflow.com/questions/22319354/how-to-create-dynamic-subdomains-for-each-user-using-node-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!