net/http: preserve original path encoding in redirects

Fixes #70758

Change-Id: I9fc6fe98c194351557c6219513918b7593899bc1
Reviewed-on: https://go-review.googlesource.com/c/go/+/720821
Reviewed-by: Damien Neil <dneil@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Mark Freeman <markfreeman@google.com>
This commit is contained in:
Sean Liao 2025-11-16 00:13:40 +00:00
parent 831af61120
commit 3e0a8e7867
2 changed files with 14 additions and 1 deletions

View file

@ -2881,6 +2881,19 @@ func TestRedirectBadPath(t *testing.T) {
} }
} }
func TestRedirectEscapedPath(t *testing.T) {
baseURL, redirectURL := "http://example.com/foo%2Fbar/", "qux%2Fbaz"
req := httptest.NewRequest("GET", baseURL, NoBody)
rr := httptest.NewRecorder()
Redirect(rr, req, redirectURL, StatusMovedPermanently)
wantURL := "/foo%2Fbar/qux%2Fbaz"
if got := rr.Result().Header.Get("Location"); got != wantURL {
t.Errorf("Redirect(%s, %s) = %s, want = %s", baseURL, redirectURL, got, wantURL)
}
}
// Test different URL formats and schemes // Test different URL formats and schemes
func TestRedirect(t *testing.T) { func TestRedirect(t *testing.T) {
req, _ := NewRequest("GET", "http://example.com/qux/", nil) req, _ := NewRequest("GET", "http://example.com/qux/", nil)

View file

@ -2408,7 +2408,7 @@ func Redirect(w ResponseWriter, r *Request, url string, code int) {
// but doing it ourselves is more reliable. // but doing it ourselves is more reliable.
// See RFC 7231, section 7.1.2 // See RFC 7231, section 7.1.2
if u.Scheme == "" && u.Host == "" { if u.Scheme == "" && u.Host == "" {
oldpath := r.URL.Path oldpath := r.URL.EscapedPath()
if oldpath == "" { // should not happen, but avoid a crash if it does if oldpath == "" { // should not happen, but avoid a crash if it does
oldpath = "/" oldpath = "/"
} }