如何在 Google Cloud 运行 中将所有 http 流量重定向到 https

How to redirect all http traffic to https in Google Cloud Run

我有一个简单的容器化 Web 应用程序(Nginx 服务于 HTML 和 Javascript),我将其部署到 Google 云 运行。

问题是,我似乎无法强制 HTTPS 连接,即使我已经验证并更新了 DNS 记录来这样做。如果用户愿意,他们仍然可以访问我的云 运行 应用程序的不安全 http 端点。

如何设置强制或重定向用户使用 HTTPS 的 Google 云 运行 服务?

LB 发送一个名为 X-Forwarded-Proto 的 header,其中包含 httphttps,因此您可以轻松地使用 301 Moved Permanently 重定向,以防您检测到.

使用 Nginx 编辑的问题示例: http://scottwb.com/blog/2013/10/28/always-on-https-with-nginx-behind-an-elb/

Go 示例代码:

func main() {
    http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
        if request.Header["X-Forwarded-Proto"][0] == "http" {
            http.Redirect(writer, request, "https://" + request.Host + request.RequestURI, http.StatusMovedPermanently)
            return
        }

        fmt.Printf("Request: %+v, headers: %+v \n", request, request.Header)

        writer.Write([]byte("hello world"))
    })
    http.ListenAndServe(":"+os.Getenv("PORT"), nil)
}