diff --git a/.changeset/happy-panthers-leave.md b/.changeset/happy-panthers-leave.md new file mode 100644 index 000000000000..4c4f8b6dad9f --- /dev/null +++ b/.changeset/happy-panthers-leave.md @@ -0,0 +1,5 @@ +--- +'@sveltejs/kit': patch +--- + +fix: redirect to path with/without trailing slash when previewing prerendered pages diff --git a/packages/kit/src/exports/vite/preview/index.js b/packages/kit/src/exports/vite/preview/index.js index f70024bce238..326818c3b181 100644 --- a/packages/kit/src/exports/vite/preview/index.js +++ b/packages/kit/src/exports/vite/preview/index.js @@ -108,8 +108,31 @@ export async function preview(vite, vite_config, svelte_config) { let prerendered = is_file(filename); if (!prerendered) { - filename += filename.endsWith('/') ? 'index.html' : '.html'; - prerendered = is_file(filename); + const has_trailing_slash = pathname.endsWith('/'); + const html_filename = `${filename}${has_trailing_slash ? 'index.html' : '.html'}`; + + let redirect; + + if (is_file(html_filename)) { + filename = html_filename; + prerendered = true; + } else if (has_trailing_slash) { + if (is_file(filename.slice(0, -1) + '.html')) { + redirect = pathname.slice(0, -1); + } + } else if (is_file(filename + '/index.html')) { + redirect = pathname + '/'; + } + + if (redirect) { + res.writeHead(307, { + location: redirect + }); + + res.end(); + + return; + } } if (prerendered) {