diff --git a/caddyhttp/push/handler.go b/caddyhttp/push/handler.go index 5fe41c10..1309eac7 100644 --- a/caddyhttp/push/handler.go +++ b/caddyhttp/push/handler.go @@ -30,9 +30,11 @@ outer: matches := httpserver.Path(urlPath).Matches(rule.Path) // Also check IndexPages when requesting a directory if !matches { - _, matches = httpserver.IndexFile(h.Root, urlPath, staticfiles.IndexPages) + indexFile, isIndexFile := httpserver.IndexFile(h.Root, urlPath, staticfiles.IndexPages) + if isIndexFile { + matches = httpserver.Path(indexFile).Matches(rule.Path) + } } - if matches { for _, resource := range rule.Resources { pushErr := pusher.Push(resource.Path, &http.PushOptions{ diff --git a/caddyhttp/push/handler_test.go b/caddyhttp/push/handler_test.go index fb32b3f6..9c34c927 100644 --- a/caddyhttp/push/handler_test.go +++ b/caddyhttp/push/handler_test.go @@ -410,7 +410,56 @@ func TestMiddlewareShouldPushIndexFile(t *testing.T) { } comparePushedResources(t, expectedPushedResources, pushingWriter.pushed) +} +func TestMiddlewareShouldNotPushIndexFileWhenNotARule(t *testing.T) { + // given + indexFile := "/index.html" + request, err := http.NewRequest(http.MethodGet, "/", nil) // Request root directory, not indexfile itself + if err != nil { + t.Fatalf("Could not create HTTP request: %v", err) + } + + root, err := ioutil.TempDir("", "caddy") + if err != nil { + t.Fatalf("Could not create temporary directory: %v", err) + } + defer os.Remove(root) + + middleware := Middleware{ + Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) { + return 0, nil + }), + Rules: []Rule{ + {Path: "dummy.html", Resources: []Resource{ + {Path: "/index.css", Method: http.MethodGet}, + }}}, + Root: http.Dir(root), + } + + indexFilePath := filepath.Join(root, indexFile) + _, err = os.Create(indexFilePath) + if err != nil { + t.Fatalf("Could not create index file: %s: %v", indexFile, err) + } + defer os.Remove(indexFilePath) + + pushingWriter := &MockedPusher{ + ResponseWriter: httptest.NewRecorder(), + returnedError: errors.New("Cannot push right now"), + } + + // when + _, err2 := middleware.ServeHTTP(pushingWriter, request) + + // then + if err2 != nil { + t.Error("Should not return error") + } + + expectedPushedResources := map[string]*http.PushOptions{} + + comparePushedResources(t, expectedPushedResources, pushingWriter.pushed) } func comparePushedResources(t *testing.T, expected, actual map[string]*http.PushOptions) {