Redirecting with Middleware, removing query params #34430
-
The problemRedirecting from a url with query params to a route without. Next merges the query params from the incoming request and appends them to the redirect url, even if you do not want them to. This was only an issue for us because our client was redirecting old wordpress pages to their new wordpress website and wordpress uses specific query params to query pages, so in order for the redirect to work the query params needed to be gone/blank. The SolutionRe-add the query params yourself and set their values to be nothing i.e. We were using a redirect file that had entries in the shape of: // redirects.js
const redirects = [
{
source: '/au/?post_type=pages&p=123456',
destination: 'https://destination.au.com/new-page-with-slug-only/',
permanent: true
},
] And then we were clearing the params with the following // pages/_middleware.js
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import redirects from '../redirects';
const redirectMap = redirects.reduce((map, redirect) => ({
...map,
[redirect.source]: redirect.destination,
}), {});
export function middleware(req: NextRequest) {
const { href, origin, searchParams } = req.nextUrl;
const redirectKey = href.replace(origin, '');
const redirect = redirectMap[redirectKey];
if (redirect) {
let params = '';
searchParams.forEach((_, key) => {
params = `${params ? `${params}&` : '?'}${key}=`;
});
return NextResponse.redirect(`${redirect}${params}`);
}
return NextResponse.next();
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Answer is in the post above ✅ |
Beta Was this translation helpful? Give feedback.
-
My site is in nuxtJS but I'm using vercel.json for redirect to a new URL i want to do the same I don't want to have old URL query params how to do that? |
Beta Was this translation helpful? Give feedback.
Answer is in the post above ✅