diff --git a/gin.go b/gin.go index a1607275..610122ae 100644 --- a/gin.go +++ b/gin.go @@ -9,6 +9,7 @@ import ( "html/template" "net" "net/http" + "net/url" "os" "path" "strings" @@ -810,16 +811,28 @@ func serveError(c *Context, code int, defaultMessage []byte) { func redirectTrailingSlash(c *Context) { req := c.Request p := req.URL.Path + // Routing matched the escaped path, so build the redirect from it too; + // otherwise an encoded slash (%2F) would turn into a real path separator. + escaped := c.engine.UseEscapedPath || (c.engine.UseRawPath && req.URL.RawPath != "") + if escaped { + p = req.URL.EscapedPath() + } if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." { prefix = sanitizePathChars(prefix) prefix = removeRepeatedChar(prefix, '/') - p = prefix + "/" + req.URL.Path + p = prefix + "/" + p } req.URL.Path = p + "/" if length := len(p); length > 1 && p[length-1] == '/' { req.URL.Path = p[:length-1] } + if escaped { + if unescaped, err := url.PathUnescape(req.URL.Path); err == nil { + req.URL.RawPath = req.URL.Path + req.URL.Path = unescaped + } + } redirectRequest(c) } diff --git a/routes_test.go b/routes_test.go index a032a2b7..8e31a951 100644 --- a/routes_test.go +++ b/routes_test.go @@ -303,6 +303,28 @@ func TestRouteRedirectTrailingSlash(t *testing.T) { assert.Equal(t, http.StatusNotFound, w.Code) } +func TestRouteRedirectTrailingSlashKeepsEscapedPath(t *testing.T) { + for _, useEscapedPath := range []bool{false, true} { + router := New() + router.UseRawPath = !useEscapedPath + router.UseEscapedPath = useEscapedPath + router.GET("/files/:name", func(c *Context) {}) + router.GET("/dirs/:name/", func(c *Context) {}) + + w := PerformRequest(router, http.MethodGet, "/files/a%2Fb/") + assert.Equal(t, http.StatusMovedPermanently, w.Code) + assert.Equal(t, "/files/a%2Fb", w.Header().Get("Location")) + + w = PerformRequest(router, http.MethodGet, "/dirs/a%2Fb") + assert.Equal(t, http.StatusMovedPermanently, w.Code) + assert.Equal(t, "/dirs/a%2Fb/", w.Header().Get("Location")) + + w = PerformRequest(router, http.MethodGet, "/files/a%2Fb/", header{Key: "X-Forwarded-Prefix", Value: "/api"}) + assert.Equal(t, http.StatusMovedPermanently, w.Code) + assert.Equal(t, "/api/files/a%2Fb", w.Header().Get("Location")) + } +} + func TestRouteRedirectFixedPath(t *testing.T) { router := New() router.RedirectFixedPath = true