首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用node express为每个用户创建动态子域?

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

Stack Overflow用户
提问于 2014-03-11 15:45:29
回答 3查看 10K关注 0票数 11

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

我该怎么做呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-07-13 12:54:30

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

代码语言:javascript
复制
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"
    ...
});
票数 15
EN

Stack Overflow用户

发布于 2019-01-30 01:45:17

代码语言:javascript
复制
// 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
票数 4
EN

Stack Overflow用户

发布于 2020-05-23 01:24:23

我来这里是因为我想完全按照OP的要求去做:

在注册时,我想在username.example.com给用户提供他的个人资料和应用程序

前面的答案是处理来自已配置子域的传入请求的方法。然而,这些答案让我想到我想要的其实很简单--如下所示:

代码语言:javascript
复制
// 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)

希望能有所帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22319354

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档