Beshoy Hanna
Beshoy Hanna

Reputation: 621

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

I have a simple containerized web app (Nginx serving HTML and Javascript) that I deployed to Google Cloud Run.

The problem is, I can't seem to force HTTPS connections even though I already verified and updated the DNS records to do so. A user can still access the unsecured http endpoint of my Cloud Run application if they wanted to.

How to set up a Google Cloud Run service that forces or redirects users to use HTTPS?

Upvotes: 5

Views: 2085

Answers (1)

petomalina
petomalina

Reputation: 2140

The LB sends a header called X-Forwarded-Proto that contains either http or https so you can easily redirect with 301 Moved Permanently in case you detect that.

Sample for the edited question with Nginx: http://scottwb.com/blog/2013/10/28/always-on-https-with-nginx-behind-an-elb/

Example Go code:

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)
}

Upvotes: 7

Related Questions