[英]How to redirect multiple subdomains to the same running express app
我正在 NodeJS 中构建一个 SaaS 应用程序并使用 Express 框架。 网站的各个成员都有一个带有自定义子域的 URL 来登录。
例如,一家名为 ABC Corp 的公司可以在abc.example.com
登录,而另一家名为 Sony 的公司可以在sony.example.com
登录
知道如何将多个子域重定向/路由到同一个应用程序实例吗?
您可以使用express-subdomain包。 假设您有一个routes
文件夹,其中包含分别导出 abc 和 sony 子域的登录路由的abc.js
和sony.js
文件,您可以在index.js
或您的 express 服务器正在侦听的任何文件中包含以下内容。
const subdomain = require('express-subdomain');
const express = require('express');
const app = express();
const abcRoutes = require('./routes/abc');
const sonyRoutes = require('./routes/sony');
const port = process.env.PORT || 3000;
// use the subdomain middleware
app.use(subdomain('abc', abcRoutes));
app.use(subdomain('sony', sonyRoutes));
// a simple get route on the top-level domain
app.get('/', (req, res) => {
res.send('Welcome to the Home Page!');
});
// add any other needed routes
module.exports = app.listen(port, () => {
console.log('Server listening on port ' + port);
});
然后您的服务器将按预期运行和工作
http://example.com/
--> 欢迎来到主页!
http://abc.example.com/login
-->(您的 abc 登录页面)
http://sony.example.com/login
-->(您的索尼登录页面)
要在本地测试子域,您需要将它们添加到/etc/hosts
文件中。 (它需要sudo
权限)
127.0.0.1 localhost
127.0.0.1 example.com
127.0.0.1 abc.example.com
127.0.0.1 sony.example.com
Windows 上/etc/hosts
文件的等效项位于%systemroot%\\system32\\drivers\\etc
有关在本地设置 localhost 域的更多详细信息, 请查看此处
您可以使用子域包做更多事情。 它接受通配符,如果您需要这样的功能,您可以使用它来检查 API 密钥。
在https://npmjs.com/package/express-subdomain查看express-subdomain
包的文档
您实际上可以处理该特定路线或范围很广,然后选择Reg Exp
(它允许您执行此app.get(new RegExp('(your|string)\\/here'), function…
)您想要重定向的然后按照以下代码正在执行的重定向操作进行操作:
response.writeHead(302, {
'Location': 'yourpath/page.html'
//add other headers here...
});
response.end();
然后您尝试使用以下应用程序处理所有请求:
express() .use(express.vhost('abc.example.com', require('/path/to/loginApp').app)) .use(express.vhost('sony.example.com', require('/path/to/loginApp').app)) .listen(80)
其中/path/to/loginApp
可以是绝对路径或相对路径。
我希望这能解决你的问题。
更新2 :
实际上,当请求进来时,请求事件会在 HTTP 服务器上引发。 所以基本上它是由 express 处理的, express.vhost
是一个中间件函数,它在 HTTP 服务器的另一个实例上引发请求事件,这就是它的工作原理。
下面是代码:
function vhost(req, res, next){ if (!req.headers.host) return next(); var host = req.headers.host.split(':')[0]; if (req.subdomains = regexp.exec(host)) { req.subdomains = req.subdomains[0].split('.').slice(0, -1); server.emit('request', req, res); } else { next(); } };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.