From e986ad2f37767bea14e86f0cb388aeba051fd9eb Mon Sep 17 00:00:00 2001 From: Ian Lewis Date: Mon, 22 Apr 2019 01:07:33 -0400 Subject: [PATCH] Redirect www.gvisor.dev to gvisor.dev --- cmd/gvisor-website/main.go | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/cmd/gvisor-website/main.go b/cmd/gvisor-website/main.go index 212256cd0..6ae1881c2 100644 --- a/cmd/gvisor-website/main.go +++ b/cmd/gvisor-website/main.go @@ -23,6 +23,7 @@ import ( "net/http" "os" "regexp" + "strings" ) var redirects = map[string]string{ @@ -56,6 +57,20 @@ func redirectWithQuery(w http.ResponseWriter, r *http.Request, target string) { http.Redirect(w, r, url, http.StatusFound) } +// hostRedirectHandler redirects the www. domain to the naked domain. +func hostRedirectHandler(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.Host, "www.") { + // Redirect to the naked domain. + r.URL.Scheme = "https" // Assume https. + r.URL.Host = r.Host[4:] // Remove the 'www.' + http.Redirect(w, r, r.URL.String(), http.StatusMovedPermanently) + return + } + h.ServeHTTP(w, r) + }) +} + // prefixRedirectHandler returns a handler that redirects to the given formated url. func prefixRedirectHandler(prefix, baseURL string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -89,11 +104,11 @@ func registerRedirects(mux *http.ServeMux) { for prefix, baseURL := range prefixHelpers { p := "/" + prefix + "/" - mux.Handle(p, prefixRedirectHandler(p, baseURL)) + mux.Handle(p, hostRedirectHandler(prefixRedirectHandler(p, baseURL))) } for path, redirect := range redirects { - mux.Handle(path, redirectHandler(redirect)) + mux.Handle(path, hostRedirectHandler(redirectHandler(redirect))) } } @@ -102,7 +117,7 @@ func registerStatic(mux *http.ServeMux, staticDir string) { if mux == nil { mux = http.DefaultServeMux } - mux.Handle("/", http.FileServer(http.Dir(staticDir))) + mux.Handle("/", hostRedirectHandler(http.FileServer(http.Dir(staticDir)))) } func envFlagString(name, def string) string {