From 3e0a8e78677a5c4035e5305446ca8f8ac3ebf2f9 Mon Sep 17 00:00:00 2001 From: Sean Liao Date: Sun, 16 Nov 2025 00:13:40 +0000 Subject: [PATCH] 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 LUCI-TryBot-Result: Go LUCI Reviewed-by: Mark Freeman --- src/net/http/serve_test.go | 13 +++++++++++++ src/net/http/server.go | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/net/http/serve_test.go b/src/net/http/serve_test.go index 4aa5b3a50f..6ade598834 100644 --- a/src/net/http/serve_test.go +++ b/src/net/http/serve_test.go @@ -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 func TestRedirect(t *testing.T) { req, _ := NewRequest("GET", "http://example.com/qux/", nil) diff --git a/src/net/http/server.go b/src/net/http/server.go index 1a7f751990..2636454958 100644 --- a/src/net/http/server.go +++ b/src/net/http/server.go @@ -2408,7 +2408,7 @@ func Redirect(w ResponseWriter, r *Request, url string, code int) { // but doing it ourselves is more reliable. // See RFC 7231, section 7.1.2 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 oldpath = "/" } -- 2.52.0