skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    import { NextResponse } from 'next/server'
    import type { NextRequest } from 'next/server'
    
    export function middleware(request: NextRequest) {
      if (request.nextUrl.pathname.endsWith('-price') || request.nextUrl.pathname.endsWith('-price/')) {
        return NextResponse.redirect(new URL(`/price/${request.nextUrl.pathname.split("-price")[0]}`, request.url), 308)
      }
      if (request.nextUrl.pathname.includes('price.php')) {
        return NextResponse.redirect(new URL(`/price/${request.url.split("price.php?brand=")[1].toLowerCase()}`, request.url), 308)
      }
    }
    

    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.


  2. You can do it using RegEx in your next.config: Regex Path Matching

    It will be something like this:

    module.exports = {
      async redirects() {
        return [
          {
            source: '/:product-name(.*)-:price(\d)',
            destination: '/:price/:product-name',
            permanent: true,
          },
        ]
      },
    }
    

    @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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search