N
Nuxt2mo ago
Talaxasy

Redirect urls with multiple slashes in the middle of url with status code 301

I'm trying to create middleware that will redirect urls with multiple slashes in the middle of url with status code 301.
4 Replies
kapa.ai
kapa.ai2mo ago
Hi @Talaxasy. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To redirect URLs with multiple slashes in the middle to their correct single-slash versions with a 301 status code in Nuxt, you can create a middleware. Here's how you can implement this: 1. Create a new file in your middleware directory, for example redirectMultipleSlashes.ts. 2. In this file, add the following code:
export default defineNuxtRouteMiddleware((to, from) => {
const path = to.fullPath
const correctedPath = path.replace(/(?<!:)\/+/g, '/')

if (path !== correctedPath) {
return navigateTo(correctedPath, { redirectCode: 301 })
}
})
export default defineNuxtRouteMiddleware((to, from) => {
const path = to.fullPath
const correctedPath = path.replace(/(?<!:)\/+/g, '/')

if (path !== correctedPath) {
return navigateTo(correctedPath, { redirectCode: 301 })
}
})
This middleware does the following: - It uses defineNuxtRouteMiddleware to create a route middleware as described in the Nuxt documentation (https://nuxt.com/docs/guide/directory-structure/middleware#middleware-order). - It checks if the current path (to.fullPath) contains multiple consecutive slashes. - If it does, it corrects the path by replacing multiple slashes with a single slash. - If the path has been corrected, it uses navigateTo to redirect to the corrected path with a 301 status code as shown in the Nuxt documentation (https://nuxt.com/docs/api/utils/navigate-to#within-route-middleware). 3. To apply this middleware globally, rename the file to redirectMultipleSlashes.global.ts. This will make it run on every route change as explained in the Nuxt documentation (https://nuxt.com/docs/guide/directory-structure/middleware#middleware-order). This solution will effectively redirect URLs with multiple slashes in the middle to their correct single-slash versions with a 301 status code. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2mo ago
<@327029731994238989> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Talaxasy
TalaxasyOP2mo ago
I created such middleware (src/middleware/01.trailing-slashes.global.ts): export default defineNuxtRouteMiddleware((to) => { const event = useRequestEvent(); let { path, query, hash } = to; const normalizedPath = path.replace(//{2,}/g, '/').replace(//+$/, '') || '/'; if (normalizedPath !== path) { const nextRoute = { path: normalizedPath, query, hash }; setResponseStatus(event, 301); return navigateTo(nextRoute, { redirectCode: 301 }); } }) But to.path already comes normalized, without slashes. For example I make req on "http://localhost:3000/produkte////atemwege/prod1" and in middleware get a "/produkte/atemwege/prod1" as you can see I already get to.path without extra slashes. I even tried with server middleware (src/server/middleware/redirects.ts): export default defineEventHandler((event) => { const pathname = getRequestURL(event).pathname; if (pathname.startsWith('/api')) return; console.log('Original URL:', event.node.req.url); console.log('New request: ' + event.node.req.originalUrl) }) But neither event.node.req.ur nor event.node.req.originalUrl comes without slashes
Oskar Lebuda
Oskar Lebuda2mo ago
I added a comment to your task. You can check what caused this error 🙂

Did you find this page helpful?