Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 735
Beshoy Hanna Avatar asked Apr 16 '19 01:04

Beshoy Hanna


People also ask

How do I redirect HTTP to HTTPS DNS?

No, you cannot redirect HTTP to HTTPS at the DNS level. This is something you have to configure on your web server (because it manages the protocol). If you don't have access to your web server, you will need to contact your web hosting provider.

How can I redirect HTTP requests to HTTPS using an classic load balancer?

Select a load balancer, and then choose HTTP Listener. Under Rules, choose View/edit rules. Choose Edit Rule to modify the existing default rule to redirect all HTTP requests to HTTPS. Or, insert a rule between the existing rules (if appropriate for your use case).


1 Answers

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)
}
like image 158
petomalina Avatar answered Sep 29 '22 07:09

petomalina