diff --git a/gokrazy.go b/gokrazy.go index 08238c9..d21fa91 100644 --- a/gokrazy.go +++ b/gokrazy.go @@ -190,11 +190,11 @@ func Boot(userBuildTimestamp string) error { } func updateListenerPairs(httpPort, httpsPort string, useTLS bool, tlsConfig *tls.Config) error { - if err := updateListeners(httpPort, useTLS, nil); err != nil { + if err := updateListeners(httpPort, httpsPort, useTLS, nil); err != nil { return err } if useTLS { - if err := updateListeners(httpsPort, useTLS, tlsConfig); err != nil { + if err := updateListeners(httpsPort, "", useTLS, tlsConfig); err != nil { return err } } diff --git a/httpsredirect.go b/httpsredirect.go index d1025b3..bb52107 100644 --- a/httpsredirect.go +++ b/httpsredirect.go @@ -5,15 +5,20 @@ import ( "net/http" ) -func httpsRedirect(w http.ResponseWriter, r *http.Request) { - host, _, _ := net.SplitHostPort(r.RemoteAddr) - ip := net.ParseIP(host) - if ip.IsLoopback() { - http.DefaultServeMux.ServeHTTP(w, r) - return - } +func httpsRedirect(redirectPort string) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + host, _, _ := net.SplitHostPort(r.RemoteAddr) + ip := net.ParseIP(host) + if ip.IsLoopback() { + http.DefaultServeMux.ServeHTTP(w, r) + return + } - r.URL.Host = r.Host - r.URL.Scheme = "https" - http.Redirect(w, r, r.URL.String(), http.StatusFound) // Redirect to https + r.URL.Host = r.Host + if redirectPort != "443" { + r.URL.Host += ":" + redirectPort + } + r.URL.Scheme = "https" + http.Redirect(w, r, r.URL.String(), http.StatusFound) // Redirect to https + } } diff --git a/listeners.go b/listeners.go index 1c5e7fd..1f8ae87 100644 --- a/listeners.go +++ b/listeners.go @@ -141,7 +141,7 @@ var ( ) // tlsConfig: tlsConfig. nil, if the listeners should not use https (e.g. for redirects) -func updateListeners(port string, tlsEnabled bool, tlsConfig *tls.Config) error { +func updateListeners(port, redirectPort string, tlsEnabled bool, tlsConfig *tls.Config) error { hosts, err := PrivateInterfaceAddrs() if err != nil { return err @@ -180,7 +180,7 @@ func updateListeners(port string, tlsEnabled bool, tlsConfig *tls.Config) error if tlsEnabled && tlsConfig == nil { // "Redirect" server srv = &http.Server{ - Handler: http.HandlerFunc(httpsRedirect), + Handler: http.HandlerFunc(httpsRedirect(redirectPort)), TLSConfig: tlsConfig, } } else {