ServeFromSubPath: Redirect to URL with subpath when subpath missing (#66724)
* ServeFromSubPath: Redirect to URL with subpath when subpath missing * Review fixes * Added tests * Use constant * change to useMiddleware * Update pkg/middleware/subpath_redirect.go --------- Co-authored-by: Carl Bergquist <carl.bergquist@gmail.com>
This commit is contained in:
co-authored by
Carl Bergquist
parent
2767d5b1c2
commit
57701fd2f2
@@ -0,0 +1,26 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
"github.com/grafana/grafana/pkg/web"
|
||||
)
|
||||
|
||||
// SubPathRedirect Redirects URLs that are missing the configured subpath to an URL that contains the subpath.
|
||||
func SubPathRedirect(cfg *setting.Cfg) web.Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
|
||||
// Direct to url with subpath if the request is missing the subpath and is not an API request.
|
||||
if !strings.HasPrefix(req.RequestURI, cfg.AppSubURL) && !strings.HasPrefix(req.RequestURI, "/api") {
|
||||
newURL := fmt.Sprintf("%s%s", cfg.AppURL, strings.TrimPrefix(req.RequestURI, "/"))
|
||||
http.Redirect(rw, req, newURL, http.StatusMovedPermanently)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(rw, req)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user