fileserver: preserve root directory matching in try_files (#8391)

This commit is contained in:
Zen Dodd 2026-11-10 18:54:23 +10:00 • committed by GitHub
parent 9ea3108377
commit 3e05c4ddf0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 39 additions and 1 deletions

View file

@ -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(`

View file

@ -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

View file

@ -63,6 +63,12 @@ func TestFileMatcher(t *testing.T) {
})
for i, tc := range []testCase{
{
path: "/",
expectedPath: "/",
expectedType: "directory",
matched: true,
},
{
path: "/.env",
expectedPath: "/.env",