簡體   English   中英

如何將多個子域重定向到同一個正在運行的 Express 應用程序

[英]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.jssony.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();


更新 1 :[根據評論和其他更新]

然后您嘗試使用以下應用程序處理所有請求:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM