add wildcard domain redirect support
1 file changed, 19 insertions(+), 3 deletions(-)
changed files
M internal/server/server.go → internal/server/server.go
@@ -8,6 +8,7 @@ "net/http" "net/url" "os" "path/filepath" + "regexp" "slices" "strconv" "strings"@@ -184,11 +185,26 @@ return nil, errors.Wrap(err, "could not create website mux") } 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)