在快速js和节点js上创建动态子域

时间:2017-03-31 19:21:53

标签: node.js express

我正在尝试创建一个网站,当用户注册时,他将拥有网址> username.mydomain.com,我尝试了多种方式,范围从vcap.me等,以及如何创建动态子域,如简单易用,

1 个答案:

答案 0 :(得分:0)

// 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