diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index 8787bf76a17c51..cef336adce2cf6 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -102,7 +102,7 @@ function shouldPreTransform(url: string, config: ResolvedConfig) { ) } -const startsWithWordCharRE = /^\w/ +const wordCharRE = /\w/ const isSrcSet = (attr: Token.Attribute) => attr.name === 'srcset' && attr.prefix === undefined @@ -125,9 +125,13 @@ const processNodeUrl = ( (url[0] === '/' && url[1] !== '/') || // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets // path will add `/a/` prefix, it will caused 404. - // rewrite before `./index.js` -> `localhost:5173/a/index.js`. - // rewrite after `../index.js` -> `localhost:5173/index.js`. - ((url[0] === '.' || startsWithWordCharRE.test(url)) && + // + // skip if url contains `:` as it implies a url protocol or Windows path that we don't want to replace. + // + // rewrite `./index.js` -> `localhost:5173/a/index.js`. + // rewrite `../index.js` -> `localhost:5173/index.js`. + // rewrite `relative/index.js` -> `localhost:5173/a/relative/index.js`. + ((url[0] === '.' || (wordCharRE.test(url[0]) && !url.includes(':'))) && originalUrl && originalUrl !== '/' && htmlPath === '/index.html') diff --git a/playground/assets/__tests__/assets.spec.ts b/playground/assets/__tests__/assets.spec.ts index fb27949dd68832..498a1d380c6358 100644 --- a/playground/assets/__tests__/assets.spec.ts +++ b/playground/assets/__tests__/assets.spec.ts @@ -513,6 +513,11 @@ test('url() contains file in publicDir, as inline style', async () => { expect(await getBg('.inline-style-public')).toContain(iconMatch) }) +test('should not rewrite non-relative urls in html', async () => { + const link = page.locator('.data-href') + expect(await link.getAttribute('href')).toBe('data:,') +}) + test.runIf(isBuild)('assets inside