diff --git a/modules/caddyhttp/rewrite/rewrite.go b/modules/caddyhttp/rewrite/rewrite.go index 95bc50468..31c977886 100644 --- a/modules/caddyhttp/rewrite/rewrite.go +++ b/modules/caddyhttp/rewrite/rewrite.go @@ -383,8 +383,13 @@ func trimPathPrefix(escapedPath, prefix string) string { iPrefix++ } - // found matching prefix, trim it - return escapedPath[iPath:] + // if we iterated through the entire prefix, we found it, so trim it + if iPath >= len(prefix) { + return escapedPath[iPath:] + } + + // otherwise we did not find the prefix + return escapedPath } func reverse(s string) string { diff --git a/modules/caddyhttp/rewrite/rewrite_test.go b/modules/caddyhttp/rewrite/rewrite_test.go index bc20c8535..5875983b6 100644 --- a/modules/caddyhttp/rewrite/rewrite_test.go +++ b/modules/caddyhttp/rewrite/rewrite_test.go @@ -225,6 +225,16 @@ func TestRewrite(t *testing.T) { input: newRequest(t, "GET", "/prefix/foo/bar"), expect: newRequest(t, "GET", "/foo/bar"), }, + { + rule: Rewrite{StripPathPrefix: "/prefix"}, + input: newRequest(t, "GET", "/prefix"), + expect: newRequest(t, "GET", ""), + }, + { + rule: Rewrite{StripPathPrefix: "/prefix"}, + input: newRequest(t, "GET", "/"), + expect: newRequest(t, "GET", "/"), + }, { rule: Rewrite{StripPathPrefix: "/prefix"}, input: newRequest(t, "GET", "/prefix/foo%2Fbar"),