如何使用Node和Express执行客户/客户端样式的子域

时间:2012-01-14 04:20:22

标签: node.js express connect hostheaders

如何允许客户使用域中的组织名称访问SaaS?

例如,一个网络应用程序example.com可能有2个客户,OrgA和OrbB。

登录后,每位客户都会被重定向到他们的网站orga.example.com / orgb.example.com。

一旦包含子域的请求到达节点服务器,我希望用单个'/'路由处理请求。在路由处理程序中,它只是检查主机头并将子域视为组织的参数。 类似的东西:

app.get "/*", app.restricted, (req, res) ->
  console.log "/* hit with #{req.url} from #{req.headers.host}"
  domains = req.headers.host.split "."
  if domains
    org = domains[0]
    console.log org
    # TODO. do something with the org name (e.g. load specific org preferences)
  res.render "app/index", { layout: "app/app" }

NB。 domains数组中的第一项是组织名称。我假设主机头中没有端口出现,现在,我不考虑如何处理非组织子域名(例如www,博客等)。

我的问题更多的是关于如何配置node / express来处理具有不同主机头的请求。这通常使用通配符别名在Apache中解决,或者在使用主机头的IIS中解决。

Apache / Rails示例是@ http://37signals.com/svn/posts/1512-how-to-do-basecamp-style-subdomains-in-rails

如何在节点中实现相同的目标?

3 个答案:

答案 0 :(得分:7)

如果你不想使用express.vhost,你可以使用http-proxy来实现更有条理的路由/端口系统

var express = require('express')
var app = express()
var fs = require('fs')

/*
Because of the way nodejitsu deals with ports, you have to put 
your proxy first, otherwise the first created webserver with an 
accessible port will be picked as the default.

As long as the port numbers here correspond with the listening 
servers below, you should be good to go. 
*/

var proxyopts = {
  router: {
    // dev
    'one.localhost': '127.0.0.1:3000',
    'two.localhost': '127.0.0.1:5000',
    // production
    'one.domain.in': '127.0.0.1:3000',
    'two.domain.in': '127.0.0.1:4000',

  }
}

var proxy = require('http-proxy')
  .createServer(proxyopts) // out port
  // port 4000 becomes the only 'entry point' for the other apps on different ports 
  .listen(4000); // in port


var one = express()
  .get('/', function(req, res) {
   var hostport = req.headers.host
   res.end(hostport)
 })
 .listen(3000)


var two = express()
  .get('/', function(req, res) {
    res.end('I AM APP FIVE THOUSAND')
  })
  .listen(5000)

答案 1 :(得分:2)

我认为任何到达节点服务器的IP地址和端口的请求都应由节点服务器处理。这就是你在apache中创建vhost的原因,以区分apache收到的请求,例如subdomain。

如果您想了解它如何处理子域(express-subdomains只有41行),请查看the source的源代码。

答案 2 :(得分:1)

我有类似的情况,虽然我有主网站example.com,用户可以登录和管理他们的网站,然后OrgA.example.com是一个面向公众的网站,将根据登录用户的行动进行更新在example.com。

我最终创建了两个单独的应用程序,并在连接中设置虚拟主机,将“example.com”指向一个应用程序,将“*”设置为另一个应用程序。 Here's an example关于如何做到这一点。