diff --git a/caddytest/integration/try_files_test.go b/caddytest/integration/try_files_test.go index c318d0ad8..9088d1364 100644 --- a/caddytest/integration/try_files_test.go +++ b/caddytest/integration/try_files_test.go @@ -46,6 +46,32 @@ func TestTryFilesErrorCodeAfterQueryItem(t *testing.T) { tester.AssertResponseCode(req, http.StatusNotFound) } +func TestTryFilesMatchesSiteRootDirectory(t *testing.T) { + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "index.html"), []byte("root"), 0o600); err != nil { + t.Fatal(err) + } + + tester := caddytest.NewTester(t) + tester.InitServer(fmt.Sprintf(` + { + skip_install_trust + admin localhost:2999 + http_port 9080 + grace_period 1ns + } + http://localhost:9080 { + root * %q + route { + try_files {path} {path}/ =404 + file_server + } + } + `, filepath.ToSlash(root)), "caddyfile") + + tester.AssertGetResponse("http://localhost:9080/", http.StatusOK, "root") +} + func TestSkippedGroupedRouteKeepsRegexpCapture(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` diff --git a/modules/caddyhttp/fileserver/matcher.go b/modules/caddyhttp/fileserver/matcher.go index 5fb4795a9..1536405fb 100644 --- a/modules/caddyhttp/fileserver/matcher.go +++ b/modules/caddyhttp/fileserver/matcher.go @@ -610,9 +610,15 @@ func (m MatchFile) cleanSplit(pattern, expanded string) (beforeSplit, afterSplit cleaned = "." } beforeSplit, afterSplit = m.firstSplit(cleaned) + patternHasTrailingSlash := strings.HasSuffix(pattern, "/") + // SanitizedPathJoin cleans the doubled slash but uses it to preserve + // the filesystem separator after the site root. + if beforeSplit == "/" && patternHasTrailingSlash { + beforeSplit += "/" + } // with "{path}", a request for "/dir/" falls through to the next entry (e.g. "{path}/index.php") - if beforeSplit != "/" && strings.HasSuffix(beforeSplit, "/") && !strings.HasSuffix(pattern, "/") { + if beforeSplit != "/" && strings.HasSuffix(beforeSplit, "/") && !patternHasTrailingSlash { return "", "", false } return beforeSplit, afterSplit, true diff --git a/modules/caddyhttp/fileserver/matcher_test.go b/modules/caddyhttp/fileserver/matcher_test.go index 5c7a1e620..dd4242865 100644 --- a/modules/caddyhttp/fileserver/matcher_test.go +++ b/modules/caddyhttp/fileserver/matcher_test.go @@ -63,6 +63,12 @@ func TestFileMatcher(t *testing.T) { }) for i, tc := range []testCase{ + { + path: "/", + expectedPath: "/", + expectedType: "directory", + matched: true, + }, { path: "/.env", expectedPath: "/.env",