diff options
author | Alan Pearce | 2024-07-09 20:32:15 +0200 |
---|---|---|
committer | Alan Pearce | 2024-07-10 20:04:21 +0200 |
commit | de704a079eb09b0b9126cb44839d1c0a34014173 (patch) | |
tree | 35d63d7df9d0f7872885d56be3a57a904bef7f4d /internal/server/server.go | |
parent | bfc935f6ea7b00c539192e486936b8ffbb5a403e (diff) | |
download | website-de704a079eb09b0b9126cb44839d1c0a34014173.tar.lz website-de704a079eb09b0b9126cb44839d1c0a34014173.tar.zst website-de704a079eb09b0b9126cb44839d1c0a34014173.zip |
add wildcard domain redirect support
Diffstat (limited to 'internal/server/server.go')
-rw-r--r-- | internal/server/server.go | 22 |
1 files changed, 19 insertions, 3 deletions
diff --git a/internal/server/server.go b/internal/server/server.go index b174c0c..6ef715b 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -8,6 +8,7 @@ import ( "net/url" "os" "path/filepath" + "regexp" "slices" "strconv" "strings" @@ -184,11 +185,26 @@ func New(runtimeConfig *Config, log *log.Logger) (*Server, error) { } if runtimeConfig.Redirect { + re := regexp.MustCompile( + "^(.*)\\." + strings.ReplaceAll(config.WildcardDomain, ".", `\.`) + "$", + ) + replace := "${0}." + config.Domains[0] loggingMux.Handle(config.BaseURL.Hostname()+"/", mux) loggingMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - path, _ := website.CanonicalisePath(r.URL.Path) - newURL := config.BaseURL.JoinPath(path) - http.Redirect(w, r, newURL.String(), http.StatusMovedPermanently) + if slices.Contains(config.Domains, r.Host) { + path, _ := website.CanonicalisePath(r.URL.Path) + newURL := config.BaseURL.JoinPath(path) + http.Redirect(w, r, newURL.String(), http.StatusMovedPermanently) + } else { + matches := re.FindSubmatchIndex([]byte(r.Host)) + if matches == nil { + http.Redirect(w, r, config.BaseURL.String(), http.StatusTemporaryRedirect) + + return + } + newHost := re.ExpandString([]byte{}, replace, r.Host, matches) + http.Redirect(w, r, string(newHost), http.StatusTemporaryRedirect) + } }) } else { loggingMux.Handle("/", mux) |