【问题标题】:Creating multiple permanent redirects to single node app route创建多个永久重定向到单节点应用程序路由
【发布时间】:2017-03-23 16:49:31
【问题描述】:

我有一组域名,我必须为其创建永久重定向到单个域,该域由在数字海洋服务器上运行的节点应用程序使用,假设它有 3 条不同的路由,例如 /a, /b, /c 和我希望我的域分别指向/a, /b, /c

另外,我还可以提供哪些其他信息以使我的问题更清楚。

【问题讨论】:

  • 你在使用 Express 吗?
  • 是的,我使用的是 Express 4

标签: node.js networking routing digital-ocean domain-name


【解决方案1】:

我不确定这是否是最佳解决方案,但在您的 node.js 应用程序中,您可以执行以下操作:

const express = require('express')

const app = express()

app.get('/', function(req, res) {

    // remove the port number if it's there
    const host = req.get('host').split(':')[0]

    if(host === "a.com") {
        res.redirect('/a')
    }
    else if(host === "b.com") {
        res.redirect('/b')
    }
    else if(host === "c.com") {
        res.redirect('/c')
    }
    else {
        // redirect somewhere else
    }
})

app.get('/a', function(req, res) {
    res.send('hello from a')
})

app.get('/b', function(req, res) {
    res.send('hello from b')
})

app.get('/c', function(req, res) {
    res.send('hello from c')
})

app.listen(3000, function() {
    console.log('Listening on 3000')
})

您可以通过更新您的 hosts 文件来在本地对此进行测试,将 a.com、b.com 和 c.com 指向 127.0.0.1。

【讨论】:

  • 我也想到了类似的解决方案,但后来我认为这里的重定向是基于用户/机器人可以更改的请求标头。这会以任何方式影响这里吗?另外,如果假设我有 5 个域名指向同一个数字海洋水滴,那么现在我如何以 express 编写,以便我的整个应用程序服务来自一个域的请求,而其他域仅用于服务特定路由,例如 /a 或可能是像 {abc}.xyz.com 这样的子域
  • 是的,可以通过弄乱标题来欺骗它。另一种选择是在你的 node.js 应用程序前面使用像 nginx 这样的反向代理,它基于域进行重定向,但我想 nginx 使用与 express 相同的标头来确定域。
  • 回答您的编辑,如果您想将域限制为某些用户,那么您需要适当的安全性 - expressjs.com/en/advanced/best-practice-security.html
  • 我不想将域限制为某些用户,我只想让他们仅路由到特定端点。
  • 您可以使用与上述相同的方法,如果主机与您想要提供该路由的主机不匹配,则重定向,但同样可以通过更改标头来绕过,如果你真的很想。除此之外,我不确定我是否害怕。
猜你喜欢
  • 1970-01-01
  • 2016-12-22
  • 2013-04-24
  • 1970-01-01
  • 2017-08-13
  • 2015-12-11
  • 1970-01-01
  • 2012-06-16
  • 2020-12-18
相关资源
最近更新 更多