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

mat*_*tgi 13 hostheaders connect node.js express

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

例如,Web应用程序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" }
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

BHB*_*HBH 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)
Run Code Online (Sandbox Code Playgroud)


mts*_*tsr 2

我认为到达节点服务器的 IP 地址和端口的任何请求都应该由节点服务器处理。这就是为什么你在 apache 中创建虚拟主机,以区分 apache 通过子域等接收到的请求。

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