all repos — homestead @ 770f198ef07726612a824112b69b7eee058e60fa

Code for my website

avoid redirect chains (http -> https, host1 -> host2)

Alan Pearce
commit

770f198ef07726612a824112b69b7eee058e60fa

parent

4999d3f3f11947994f81f128714f4e2096fdd252

1 file changed, 30 insertions(+), 9 deletions(-)

changed files
M internal/server/server.gointernal/server/server.go
@@ -47,8 +47,9 @@ }
type Server struct { *http.Server - runtimeConfig *Config - config *cfg.Config + redirectHandler func(http.ResponseWriter, *http.Request) + runtimeConfig *Config + config *cfg.Config } func applyDevModeOverrides(config *cfg.Config, runtimeConfig *Config) {
@@ -59,9 +60,13 @@ config.Domains = strings.Split(runtimeConfig.Domains, ",")
} else { config.Domains = []string{runtimeConfig.ListenAddress} } + scheme := "http" + if runtimeConfig.TLS { + scheme = "https" + } config.BaseURL = cfg.URL{ URL: &url.URL{ - Scheme: "http", + Scheme: scheme, Host: runtimeConfig.ListenAddress, }, }
@@ -76,9 +81,22 @@ }
func serverHeaderHandler(wrappedHandler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + log.Debug( + "headers", + "proto", + r.Header.Get("X-Forwarded-Proto"), + "host", + r.Header.Get("X-Forwarded-Host"), + "scheme", + r.URL.Scheme, + "secure", + r.TLS != nil, + ) + log.Debug("host", "request", r.Host, "header", r.Header.Get("Host")) if r.ProtoMajor >= 2 && r.Header.Get("Host") != "" { // net/http does this for HTTP/1.1, but not h2c // TODO: check with HTTP/2.0 (i.e. with TLS) + log.Debug("host", "request", r.Host, "header", r.Header.Get("Host")) r.Host = r.Header.Get("Host") r.Header.Del("Host") }
@@ -174,12 +192,14 @@ if err != nil {
return nil, errors.Wrap(err, "could not create website mux") } + redirectHandler := func(w http.ResponseWriter, r *http.Request) { + path, _ := website.CanonicalisePath(r.URL.Path) + newURL := config.BaseURL.JoinPath(path) + http.Redirect(w, r, newURL.String(), 301) + } if runtimeConfig.Redirect { loggingMux.Handle(config.BaseURL.Hostname()+"/", mux) - loggingMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - newURL := config.BaseURL.JoinPath(r.URL.String()) - http.Redirect(w, r, newURL.String(), 301) - }) + loggingMux.HandleFunc("/", redirectHandler) } else { loggingMux.Handle("/", mux) }
@@ -205,8 +225,9 @@ IdleTimeout: 15 * time.Minute,
}, ), 0), }, - config: config, - runtimeConfig: runtimeConfig, + redirectHandler: redirectHandler, + config: config, + runtimeConfig: runtimeConfig, }, nil }