Talaxasy
Redirect urls with multiple slashes in the middle of url with status code 301
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
6 replies