diff options
author | Ian Lewis <ianmlewis@gmail.com> | 2019-04-22 01:07:33 -0400 |
---|---|---|
committer | Ian Lewis <ianlewis@google.com> | 2019-04-23 11:54:43 +0900 |
commit | e986ad2f37767bea14e86f0cb388aeba051fd9eb (patch) | |
tree | 36894041517cbf123e2a177d39c0786302412554 | |
parent | c010346c76457ed89b658e6030dd597cc5d6dcca (diff) |
Redirect www.gvisor.dev to gvisor.dev
-rw-r--r-- | cmd/gvisor-website/main.go | 21 |
1 files 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 { |