My website is changing URL structure and I have 1000s of pages. For SEO I would like to set up a Regex redirect in my next.config.js file, but the official documentation doesn’t really help my case because my pages have the following structure:
/product-name-price/
The new structure will be:
/price/product-name
UPDATE:
I’ve managed to get /product-name-price
to redirect to /price/product-name-price
with the following changes to next.config.js:
async redirects() {
return [
{
source: '/:product',
destination: '/price/:product',
permanent: true,
}
]
}
How do I manipulate the :product
parameter within the next.config.js file to exclude the -price
part of product-name-price
so that my final url will be /price/product-name
?
2
Answers
I resolved this using middleware since it doesn't seem to be possible to modify the parameter of the redirect destination in next.config.js.
The first conditional checks if the request pathname ends with
-price
, and then redirects to the same path without-price
by splitting the string, with status code 308.The second conditional checks to see if the request pathname contains
price.php
, in which case it also has query parameter of 'brand'. It takes the value of this parameter and redirects to the/price/product-name
structure, where 'product-name' is equal to the value of 'brand', again by splitting the string.I have used 308 redirect for SEO purposes, to indicate it is a permanent redirect to Google.
You can do it using RegEx in your
next.config
: Regex Path MatchingIt will be something like this:
@user3536141, I can try to help you with a more accurate example if you provide the use case and its variations (if there is some).