Golang Naked Redirect WWW Middleware
Last updated: Mar 2, 2024It is important to make sure you site’s URL is either naked yoursite.com or with www. like www.yoursite.com. One should redirect to the other and you should keep is consistent for SEO.
If you redirect naked to www., and you use Go, you can use the following Go middleware to have all naked requests redirect with 301 to www.:
func RedirectNakedToWWW(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// if host doesn't have www. redirect
if !strings.HasPrefix(r.Host, "www.") {
http.Redirect(w, r, fmt.Sprintf("https://www.%s", r.Host)+r.URL.String(), http.StatusMovedPermanently)
return
}
handler.ServeHTTP(w, r)
})
}
Need to print shipping labels on your site?
Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.