Google Cloud Platform,Golang灵活环境仅支持自定义域名的HTTPS。

huangapple go评论132阅读模式
英文:

Google Cloud Platform, Golang Flexible Environment HTTPS only for custom domain

问题

我通过在GCP上运行gcloud app deploy命令,顺利部署了我的应用程序。默认情况下,它使用了灵活环境。昨天,我进行了必要的自定义设置,为该应用程序添加了自定义域名和SSL证书。目前,当我访问以下任何一个网址时,http://example.comhttps://example.com,它都可以正常工作。但是,我还想强制用户使用https。目前,http请求仍然有效,我希望将它们重定向到https。当用户尝试使用http或没有任何内容(如example.com)访问网站时,我希望将其重定向到https://example.com。如何实现这一目标?

以下是我的app.yaml文件内容:

api_version: go1
env: flex
runtime: go

我已经尝试使用handlerssecure属性,但似乎它们在灵活环境中无效。

谢谢。

英文:

I have deployed my application without hassle just by running gcloud app deploy command on GCP. Which takes the flexible environment as default. Yesterday I made the necessary customizations to have a custom domain for this app with ssl. Currently it works when I go to any of the following, http://example.com, https://example.com but I also want to force people to use https. Currently the http requests work as they are, I want them to be directed to https. I want to direct any user to https://example.com when they try to go to the website with http or without anything at all like example.com. How can this be achieved?

Here's my app.yaml:

api_version: go1
env: flex
runtime: go

I already tried to use handlers and secure attributes but it seems they are not valid for flexible environment.

Thanks.

答案1

得分: 2

目前,灵活环境不支持使用 app.yaml 来实现仅通过 HTTPS 进行重定向。但是,可以通过在服务器代码中使用类似以下的函数来实现:

func directToHttps(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
    if r.URL.Scheme == "https" || strings.HasPrefix(r.Proto, "HTTPS") || r.Header.Get("X-Forwarded-Proto") == "https" {
        next(w, r)
    } else {
        target := "https://" + r.Host + r.URL.Path

        http.Redirect(w, r, target,
            http.StatusTemporaryRedirect)
    }
}

我使用 negroni 将这个函数包装到我的处理程序中。

可以在这里找到一个可工作的示例:https://github.com/malisit/munhasir

英文:

Currently, flexible environment does not support HTTPS only directing by using app.yaml. However, this can be achieved in the server code by using a function like this,

func directToHttps(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	if r.URL.Scheme == "https" || strings.HasPrefix(r.Proto, "HTTPS") || r.Header.Get("X-Forwarded-Proto") == "https" {
		next(w, r)
	} else {
		target := "https://" + r.Host + r.URL.Path

		http.Redirect(w, r, target,
			http.StatusTemporaryRedirect)
	}
}

I wrapped this function to my handlers with negroni.

Working example can be found here: https://github.com/malisit/munhasir

huangapple
  • 本文由 发表于 2017年5月3日 07:56:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/43748981.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定