Google Cloud 运行 for Anthos (Knative) 未在 https 请求上正确设置 X-Forwarded-Proto header

Google Cloud Run for Anthos (Knative) not setting X-Forwarded-Proto header correctly on https requests

我有一个 django 应用程序 运行ning 在 Google 云 运行(在 Kube 集群中),通过 Docker 由 uwsgi 提供服务(但我试过manage.py 运行服务器和它是一样的)。默认情况下,云 运行 接受 http 和 https 上的连接。

我想将用户重定向到 https 版本,但云 运行 并未正确设置 headers。

我有一个处理程序 returns headers 通过:json.dumps(request.headers.__dict__['_store'])

返回的相关headers是:

"x-forwarded-proto": ["X-Forwarded-Proto", "http"]

但是即使我访问网站的 https 版本,值 http 也不会改变。

django 应该如何正确检测云端的 http 请求 运行?我无法使用

SECURE_PROXY_SSL_HEADER

检测 http 请求并将其重定向到 https,因为它们看起来都是 http 请求,因此您最终会陷入重定向循环。

但是,如果我在 post 中遵循 links:https://www.jhanley.com/google-cloud-run-https-part-2/

他们的“显示 headers” link 值确实从 http 更改为 https。这是django的事吗?还是“kube 上的云 运行”?

在纯云上托管有问题的应用程序 运行 并访问 http 版本会内部重定向到 HTTPS 版本并给出原因:Non-Authoritative-Reason:HSTS

这正是我想要实现的目标。我得到的 headers 似乎来自内部路由,而不是在 Anthos 模式下 运行ning 时的原始请求本身。

article you linked 似乎与“云 运行(完全托管)”有关,但您没有使用它。 Cloud 运行 for Anthos (Knative) 有一个完全不同的堆栈来处理请求和 HTTPS 终止。所以请无视。


以下是如何使用 Knative 管理的 TLS 证书(由 Let's Encrypt 颁发)创建域并执行 HTTP→ HTTPS 重定向。

此过程在官方 Cloud 运行 文档中有说明:https://cloud.google.com/run/docs/gke/managed-tls

  1. 确保您的集群是 1.17.7-gke.15 和更新版本。默认情况下启用这些版本的“托管证书”功能。

  2. 为您的服务创建域映射。 (您可以在 Cloud Console 上执行此操作)

  3. 将您域的 DNS 记录指向给您的 IP 地址(可以在 gke-system Kubernetes 命名空间中找到的网关 IP 服务)

  4. 系统会在后台为您的域自动提供 TLS 证书(每 80 天左右更新一次)

  5. 要设置 HTTP→HTTPS 重定向,follow these instructions 这需要您 运行:

    kubectl annotate domainmappings [YOUR_DOMAIN] domains.cloudrun.com/httpsRedirect=Enabled
    

    这基本上是在 Kubernetes 中向 DomainMapping object 添加注释。

    这会在您的集群中配置入口网关来为您进行重定向。 您不需要阅读x-forwarded-protoheader并采取行动。

这个问题是已知的,我在几个月前就已经报告过了。您可以在 Google Cloud 运行 上跟踪它 here 以获得 Anthos 问题跟踪器。

我找到的解决此问题的解决方法是通过检查 window.location.protocol 的值是否为 http 并重写位置,在前端使用 JavaScript 进行重定向:

window.location = "https://" + window.location.hostname + window.location.pathname + window.location.search;