如何使用node express为每个用户创建动态子域?

时间:2014-03-11 07:45:29

标签: node.js dynamic subdomain

在注册时,我想在username.example.com上向用户提供他的个人资料和应用程序 我已经在我的域名提供商网站上创建了通配符dns。

我该怎么做?

3 个答案:

答案 0 :(得分:7)

如果将Node.js与Express.js一起使用,则:

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"
    ...
});

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我到达这里是因为我想做OP要求的事情:

在注册时,我想通过username.example.com向用户提供其个人资料和应用

先前的答案是处理来自已预配置的子域的传入请求的方法。但是,答案使我开始思考我想要的东西实际上非常简单-这是这样:

// Creating the subdomain

app.post('/signup', (req, res) => {
  const { username } = req.body;

  //... do some validations / verifications
  // e.g. uniqueness check etc

  res.redirect(`https://${username}.${req.hostname}`);
})

// Handling requests from the subdomains: 2 steps
// Step 1: forward the request to other internal routes e.g. with patterns like `/subdomain/:subdomain_name/whatever-path`

app.use((req, res, next) {

  // if subdomains
  if (req.subdomains.length) {

    // this is trivial, you should filtering out things like `www`, `app` or anything that your app already uses.

    const subdomain = req.subdomains.join('.');

    // forward to internal url by reconstructing req.url

    req.url = `/subdomains/${subdomain}${req.url}`
  }
  return next()
});

// Handling requests from the subdomains: 2 steps
// Step 2: Have router setup for handling such routes
// you must have created the subdomainRoutes somewhere else

app.use('/subdomains/:subdomain', subdomainRoutes)

希望有帮助。