go 29 lines · 5 steps

How a www-to-apex redirect middleware works in Gin

A Gin middleware that permanently redirects www hostnames to their apex domain while preserving scheme and path.

Explained by highlit
1package middleware
2 
3import (
4 "net/http"
5 "strings"
6 
7 "github.com/gin-gonic/gin"
8)
9 
10func RedirectWWW() gin.HandlerFunc {
11 return func(c *gin.Context) {
12 host := c.Request.Host
13 if !strings.HasPrefix(host, "www.") {
14 c.Next()
15 return
16 }
17 
18 apex := strings.TrimPrefix(host, "www.")
19 
20 scheme := "http"
21 if c.Request.TLS != nil || c.GetHeader("X-Forwarded-Proto") == "https" {
22 scheme = "https"
23 }
24 
25 target := scheme + "://" + apex + c.Request.URL.RequestURI()
26 c.Redirect(http.StatusMovedPermanently, target)
27 c.Abort()
28 }
29}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Returning a closure that captures nothing lets a middleware factory produce a reusable handler.
  2. 2Detecting HTTPS behind a proxy means checking X-Forwarded-Proto, not just the raw TLS connection.
  3. 3A 301 with the original RequestURI keeps the visitor's path and query intact across the redirect.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a www-to-apex redirect middleware works in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code