Add force flag to server redirects config

Fixes #7778
This commit is contained in:
Bjørn Erik Pedersen 2020-10-05 17:56:28 +02:00
parent ee090c0940
commit 5e2a547cb5
3 changed files with 30 additions and 11 deletions

View file

@ -376,8 +376,26 @@ func (f *fileServer) createEndpoint(i int) (*http.ServeMux, string, string, erro
} }
if redirect := f.c.serverConfig.MatchRedirect(requestURI); !redirect.IsZero() { if redirect := f.c.serverConfig.MatchRedirect(requestURI); !redirect.IsZero() {
doRedirect := true
// This matches Netlify's behaviour and is needed for SPA behaviour. // This matches Netlify's behaviour and is needed for SPA behaviour.
// See https://docs.netlify.com/routing/redirects/rewrites-proxies/ // See https://docs.netlify.com/routing/redirects/rewrites-proxies/
if !redirect.Force {
path := filepath.Clean(strings.TrimPrefix(requestURI, u.Path))
fi, err := f.c.hugo().BaseFs.PublishFs.Stat(path)
if err == nil {
if fi.IsDir() {
// There will be overlapping directories, so we
// need to check for a file.
_, err = f.c.hugo().BaseFs.PublishFs.Stat(filepath.Join(path, "index.html"))
doRedirect = err != nil
} else {
doRedirect = false
}
}
}
if doRedirect {
if redirect.Status == 200 { if redirect.Status == 200 {
if r2 := f.rewriteRequest(r, strings.TrimPrefix(redirect.To, u.Path)); r2 != nil { if r2 := f.rewriteRequest(r, strings.TrimPrefix(redirect.To, u.Path)); r2 != nil {
requestURI = redirect.To requestURI = redirect.To
@ -388,6 +406,7 @@ func (f *fileServer) createEndpoint(i int) (*http.ServeMux, string, string, erro
http.Redirect(w, r, redirect.To, redirect.Status) http.Redirect(w, r, redirect.To, redirect.Status)
return return
} }
}
} }
@ -416,7 +435,6 @@ func (f *fileServer) createEndpoint(i int) (*http.ServeMux, string, string, erro
fileserver := decorate(http.FileServer(fs)) fileserver := decorate(http.FileServer(fs))
mu := http.NewServeMux() mu := http.NewServeMux()
if u.Path == "" || u.Path == "/" { if u.Path == "" || u.Path == "/" {
mu.Handle("/", fileserver) mu.Handle("/", fileserver)
} else { } else {

View file

@ -184,6 +184,7 @@ type Redirect struct {
From string From string
To string To string
Status int Status int
Force bool
} }
func (r Redirect) IsZero() bool { func (r Redirect) IsZero() bool {

View file

@ -360,10 +360,10 @@ Note that a `status` code of 200 will trigger a [URL rewrite](https://docs.netli
from = "/myspa/**" from = "/myspa/**"
to = "/myspa/" to = "/myspa/"
status = 200 status = 200
force = false
{{< /code-toggle >}} {{< /code-toggle >}}
{{< new-in "0.76.0" >}} Setting `force=true` will make a redirect even if there is existing content in the path. Note that before Hugo 0.76 `force` was the default behaviour, but this is inline with how Netlify does it.
## Configure Title Case ## Configure Title Case