From dae6d0aa63d436da747cbc67ad9e735b0d1934f0 Mon Sep 17 00:00:00 2001 From: sapphi-red <49056869+sapphi-red@users.noreply.github.com> Date: Mon, 25 Sep 2023 18:05:14 +0900 Subject: [PATCH] fix: allow path ending with .html to fallback to index.html --- .../vite/src/node/server/middlewares/htmlFallback.ts | 11 ++++++++--- playground/assets/__tests__/assets.spec.ts | 4 ++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/vite/src/node/server/middlewares/htmlFallback.ts b/packages/vite/src/node/server/middlewares/htmlFallback.ts index 21f5b6128a3491..1cd653f05eb896 100644 --- a/packages/vite/src/node/server/middlewares/htmlFallback.ts +++ b/packages/vite/src/node/server/middlewares/htmlFallback.ts @@ -26,11 +26,16 @@ export function htmlFallbackMiddleware( return spaFallback ? `/index.html` : request.url }, }, - // don't rewrite paths ending with .html { from: /\.html$/, - to({ request }: any) { - return request.url + to({ parsedUrl, request }: any) { + // .html files are not handled by serveStaticMiddleware + // so we need to check if the file exists + const pathname = decodeURIComponent(parsedUrl.pathname) + if (fs.existsSync(path.join(root, pathname))) { + return request.url + } + return '/index.html' }, }, ], diff --git a/playground/assets/__tests__/assets.spec.ts b/playground/assets/__tests__/assets.spec.ts index 76d8606c0754c8..af939f028ce660 100644 --- a/playground/assets/__tests__/assets.spec.ts +++ b/playground/assets/__tests__/assets.spec.ts @@ -52,6 +52,10 @@ test('should get a 404 when using incorrect case', async () => { ) }) +test('should fallback to index.html when accessing non-existant html file', async () => { + expect((await fetchPath('doesnt-exist.html')).status).toBe(200) +}) + describe('injected scripts', () => { test('@vite/client', async () => { const hasClient = await page.$(