mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-25 15:15:19 +00:00
fix(nuxt): respect redirects which differ only by trailing slash (#18593)
Co-authored-by: Daniel Roe <daniel@roe.dev>
This commit is contained in:
parent
e2fc6f267d
commit
f5a3d7968c
@ -176,7 +176,7 @@ export default defineNuxtPlugin(async (nuxtApp) => {
|
||||
})])
|
||||
} else if (process.server) {
|
||||
const currentURL = to.fullPath || '/'
|
||||
if (!isEqual(currentURL, initialURL)) {
|
||||
if (!isEqual(currentURL, initialURL, { trailingSlash: true })) {
|
||||
const event = await callWithNuxt(nuxtApp, useRequestEvent)
|
||||
const options = { redirectCode: event.node.res.statusCode !== 200 ? event.node.res.statusCode || 302 : 302 }
|
||||
await callWithNuxt(nuxtApp, navigateTo, [currentURL, options])
|
||||
|
@ -321,9 +321,17 @@ describe('legacy async data', () => {
|
||||
|
||||
describe('navigate', () => {
|
||||
it('should redirect to index with navigateTo', async () => {
|
||||
const { headers } = await fetch('/navigate-to/', { redirect: 'manual' })
|
||||
const { headers, status } = await fetch('/navigate-to/', { redirect: 'manual' })
|
||||
|
||||
expect(headers.get('location')).toEqual('/')
|
||||
expect(status).toEqual(301)
|
||||
})
|
||||
|
||||
it('respects redirects + headers in middleware', async () => {
|
||||
const res = await fetch('/navigate-some-path/', { redirect: 'manual', headers: { 'trailing-slash': 'true' } })
|
||||
expect(res.headers.get('location')).toEqual('/navigate-some-path')
|
||||
expect(res.status).toEqual(307)
|
||||
expect(await res.text()).toMatchInlineSnapshot('"<!DOCTYPE html><html><head><meta http-equiv=\\"refresh\\" content=\\"0; url=/navigate-some-path\\"></head></html>"')
|
||||
})
|
||||
})
|
||||
|
||||
|
@ -1,5 +1,10 @@
|
||||
import { withoutTrailingSlash } from 'ufo'
|
||||
|
||||
export default defineNuxtRouteMiddleware(async (to) => {
|
||||
const nuxtApp = useNuxtApp()
|
||||
if (useRequestHeaders(['trailing-slash'])['trailing-slash'] && to.fullPath.endsWith('/')) {
|
||||
return navigateTo(withoutTrailingSlash(to.fullPath), { redirectCode: 307 })
|
||||
}
|
||||
if (to.path.startsWith('/redirect/')) {
|
||||
await new Promise(resolve => setTimeout(resolve, 100))
|
||||
return navigateTo(to.path.slice('/redirect/'.length - 1))
|
||||
|
2
test/fixtures/basic/pages/navigate-to.vue
vendored
2
test/fixtures/basic/pages/navigate-to.vue
vendored
@ -3,5 +3,5 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
await navigateTo('/', { replace: true })
|
||||
await navigateTo('/', { replace: true, redirectCode: 301 })
|
||||
</script>
|
||||
|
Loading…
Reference in New Issue
Block a user