Skip to content

Commit

Permalink
rewrite: Don't add / in Caddyfile, do it after replacer
Browse files Browse the repository at this point in the history
  • Loading branch information
francislavoie committed Oct 24, 2024
1 parent eaaa2e5 commit a2066ad
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 3 deletions.
3 changes: 0 additions & 3 deletions modules/caddyhttp/rewrite/caddyfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,6 @@ func parseCaddyfileURI(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, err
return nil, h.ArgErr()
}
rewr.StripPathPrefix = args[1]
if !strings.HasPrefix(rewr.StripPathPrefix, "/") {
rewr.StripPathPrefix = "/" + rewr.StripPathPrefix
}

case "strip_suffix":
if len(args) != 2 {
Expand Down
3 changes: 3 additions & 0 deletions modules/caddyhttp/rewrite/rewrite.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,9 @@ func (rewr Rewrite) Rewrite(r *http.Request, repl *caddy.Replacer) bool {
// strip path prefix or suffix
if rewr.StripPathPrefix != "" {
prefix := repl.ReplaceAll(rewr.StripPathPrefix, "")
if !strings.HasPrefix(prefix, "/") {
prefix = "/" + prefix
}
mergeSlashes := !strings.Contains(prefix, "//")
changePath(r, func(escapedPath string) string {
escapedPath = caddyhttp.CleanPath(escapedPath, mergeSlashes)
Expand Down
5 changes: 5 additions & 0 deletions modules/caddyhttp/rewrite/rewrite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,11 @@ 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/foo/bar"),
expect: newRequest(t, "GET", "/foo/bar"),
},
{
rule: Rewrite{StripPathPrefix: "/prefix"},
input: newRequest(t, "GET", "/prefix"),
Expand Down

0 comments on commit a2066ad

Please sign in to comment.