Skip to content

Commit 13a3768

Browse files
authored
rewrite: use escaped path, fix #5278 (#5504)
* use escaped path while rewriting Signed-off-by: TP-O <[email protected]> * restore line break --------- Signed-off-by: TP-O <[email protected]>
1 parent e8352ae commit 13a3768

File tree

2 files changed

+20
-12
lines changed

2 files changed

+20
-12
lines changed

modules/caddyhttp/rewrite/rewrite.go

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -195,16 +195,10 @@ func (rewr Rewrite) Rewrite(r *http.Request, repl *caddy.Replacer) bool {
195195
var newPath, newQuery, newFrag string
196196

197197
if path != "" {
198-
// Since the 'uri' placeholder performs a URL-encode,
199-
// we need to intercept it so that it doesn't, because
200-
// otherwise we risk a double-encode of the path.
201-
uriPlaceholder := "{http.request.uri}"
202-
if strings.Contains(path, uriPlaceholder) {
203-
tmpUri := r.URL.Path
204-
if r.URL.RawQuery != "" {
205-
tmpUri += "?" + r.URL.RawQuery
206-
}
207-
path = strings.ReplaceAll(path, uriPlaceholder, tmpUri)
198+
// replace the `path` placeholder to escaped path
199+
pathPlaceholder := "{http.request.uri.path}"
200+
if strings.Contains(path, pathPlaceholder) {
201+
path = strings.ReplaceAll(path, pathPlaceholder, r.URL.EscapedPath())
208202
}
209203

210204
newPath = repl.ReplaceAll(path, "")
@@ -232,7 +226,11 @@ func (rewr Rewrite) Rewrite(r *http.Request, repl *caddy.Replacer) bool {
232226
// update the URI with the new components
233227
// only after building them
234228
if pathStart >= 0 {
235-
r.URL.Path = newPath
229+
if path, err := url.PathUnescape(newPath); err != nil {
230+
r.URL.Path = newPath
231+
} else {
232+
r.URL.Path = path
233+
}
236234
}
237235
if qsStart >= 0 {
238236
r.URL.RawQuery = newQuery

modules/caddyhttp/rewrite/rewrite_test.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,16 @@ func TestRewrite(t *testing.T) {
5959
input: newRequest(t, "GET", "/"),
6060
expect: newRequest(t, "GET", "foo"),
6161
},
62+
{
63+
rule: Rewrite{URI: "{http.request.uri}"},
64+
input: newRequest(t, "GET", "/bar%3Fbaz?c=d"),
65+
expect: newRequest(t, "GET", "/bar%3Fbaz?c=d"),
66+
},
67+
{
68+
rule: Rewrite{URI: "{http.request.uri.path}"},
69+
input: newRequest(t, "GET", "/bar%3Fbaz"),
70+
expect: newRequest(t, "GET", "/bar%3Fbaz"),
71+
},
6272
{
6373
rule: Rewrite{URI: "/foo{http.request.uri.path}"},
6474
input: newRequest(t, "GET", "/bar"),
@@ -323,7 +333,7 @@ func TestRewrite(t *testing.T) {
323333
input: newRequest(t, "GET", "/foo/findme%2Fbar"),
324334
expect: newRequest(t, "GET", "/foo/replaced%2Fbar"),
325335
},
326-
336+
327337
{
328338
rule: Rewrite{PathRegexp: []*regexReplacer{{Find: "/{2,}", Replace: "/"}}},
329339
input: newRequest(t, "GET", "/foo//bar///baz?a=b//c"),

0 commit comments

Comments
 (0)