lib/httpserver: use 302 redirects instead of 301 redirects

Incorrect 301 redirects can be cached by user agents such as web browsers.
This can complicate recovery procedure after the incorrect redirect is fixed,
e.g. web browser cache must be reset.

The related issue - https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1752
This commit is contained in:
Aliaksandr Valialkin 2022-10-01 16:53:33 +03:00
parent e03a924236
commit 93e84a1c57
No known key found for this signature in database
GPG key ID: A72BEC6CD3D0DED1
3 changed files with 10 additions and 7 deletions

View file

@ -168,7 +168,7 @@ func (rh *requestHandler) handler(w http.ResponseWriter, r *http.Request) bool {
if strings.HasPrefix(r.URL.Path, "/api/v1/") {
redirectURL = alert.APILink()
}
httpserver.RedirectPermanent(w, "/"+redirectURL)
httpserver.Redirect(w, "/"+redirectURL)
return true
}
}

View file

@ -296,7 +296,7 @@ func selectHandler(qt *querytracer.Tracer, startTime time.Time, w http.ResponseW
_ = r.ParseForm()
suffix := strings.Replace(p.Suffix, "prometheus/", "../prometheus/", 1)
newURL := suffix + "/?" + r.Form.Encode()
httpserver.RedirectPermanent(w, newURL)
httpserver.Redirect(w, newURL)
return true
}
if strings.HasPrefix(p.Suffix, "vmui/") || strings.HasPrefix(p.Suffix, "prometheus/vmui/") {
@ -350,7 +350,7 @@ func selectHandler(qt *querytracer.Tracer, startTime time.Time, w http.ResponseW
if p.Suffix == "prometheus/vmalert" {
path := "../" + p.Suffix + "/"
httpserver.RedirectPermanent(w, path)
httpserver.Redirect(w, path)
return true
}
if strings.HasPrefix(p.Suffix, "prometheus/vmalert/") {

View file

@ -248,7 +248,7 @@ func handlerWrapper(s *server, w http.ResponseWriter, r *http.Request, rh Reques
// This is needed for proper handling of relative urls in web browsers.
// Intentionally ignore query args, since it is expected that the requested url
// is composed by a human, so it doesn't contain query args.
RedirectPermanent(w, prefix)
Redirect(w, prefix)
return
}
if !strings.HasPrefix(path, prefix) {
@ -681,11 +681,14 @@ func GetRequestURI(r *http.Request) string {
return requestURI + delimiter + queryArgs
}
// RedirectPermanent redirects to the given url using 301 status code.
func RedirectPermanent(w http.ResponseWriter, url string) {
// Redirect redirects to the given url.
func Redirect(w http.ResponseWriter, url string) {
// Do not use http.Redirect, since it breaks relative redirects
// if the http.Request.URL contains unexpected url.
// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/2918
w.Header().Set("Location", url)
w.WriteHeader(http.StatusMovedPermanently)
// Use http.StatusFound instead of http.StatusMovedPermanently,
// since browsers can cache incorrect redirects returned with StatusMovedPermanently.
// This may require browser cache cleaning after the incorrect redirect is fixed.
w.WriteHeader(http.StatusFound)
}