使用 cloudflare 将请求路由到不同的 Web 应用程序

Routing requests using cloudflare to different web applications

我目前有两个在 cloudflare 中使用以下 CNAME 设置的 Web 应用程序。两者都是 keystonejs 应用程序。

app1.example.com ===pointing to ===> AWS ALB 1
app2.example.com ===pointing to ===> AWS ALB 2

我设置了 Cloudflare Enterprise,因此我可以在我的页面规则中使用 "Render Override" 功能。我使用以下内容设置了 2 个页面规则:

www.example.com ===render override ===> app1.example.com
www.example.com/app2/* ===render override ===> app2.example.com

现在为了访问 app2.example.com 上的 keystonejs 应用程序。使用 app2.example.com/pa

调用应用程序

我面临的问题是渲染覆盖不允许我使用子路径,我不想使用转发规则。我是否需要让我的 keystone 应用程序可以通过根 url,即 app2.example.com/ 访问?还是有另一种方法可以做到这一点?否则,我需要使用反向代理吗?比如 nginx ? 谢谢

注意:由于您是企业客户,我强烈建议您联系 Cloudflare 的客户成功经理 and/or 解决方案工程师。他们在那里帮助解决这些类型的问题。也就是说,为了 self-serve 客户的利益,我将在这里回答这个问题。

我认为当你说 "Render Override" 时,你实际上是指 "Resolve Override"。此设置更改请求的 DNS 查找,以便将其路由到与正常情况不同的源 IP 地址。

请注意,Resolve Override 不会以任何方式重写请求;它只会将其路由到不同的服务器。因此,对 www.example.com/app2/foo 的请求将转到服务器 app2.example.com,但路径仍将是 /app2/foo(而不是 /foo),并且 Host header 仍然是 Host: www.example.com.

听起来您确实希望 /app2/* 重写为 /pa/*,此外还需要重定向到其他来源。您可以使用 Cloudflare Workers 来完成此操作,它允许您在 Cloudflare 的边缘执行任意 JavaScript。脚本可能如下所示:

addEventListener("fetch", event => {
  event.respondWith(handle(event.request));
});

async function handle(request) {
  let url = new URL(request.url)  // parse the URL

  if (url.pathname.startsWith("/app2/")) {
    // Override the target hostname.
    url.host = "app2.example.com"

    // Replace /app2/ with /pb/ in the path.
    url.pathname = "/pb/" + url.pathname.slice("/app2/".length)

    // Send the request on to origin.
    return fetch(url, request)
  } else {
    // Just override the hostname.
    url.host = "app1.example.com"

    // Send the request on to origin.
    return fetch(url, request)
  }
}

部署后,您可以删除解决覆盖页面规则,因为它们现在已被 Worker 脚本覆盖。

请注意,上面的脚本除了路径之外,实际上确实重写了Host header。如果您希望 Host header 保持 www.example.com,则需要使用 the cf.resolveOverride option。这仅适用于企业客户;如果您需要帮助使用它,请询问您的 CSM 或 SE。但是,在大多数情况下,您实际上希望 Host header 被重写,所以您可能不需要这个。