skip to Main Content

I have a requirement from a customer SEO to redirect all pages from 308 to 301. Project is developed in NextJS 13 with page folder. I’ve handled most of the cases (old pages to new pages after migration) in middleware.ts using

return NextResponse.redirect(new URL(address.destination), { status: 301 });

General page structure is following: xyz.com/offer/:brand/:model/

The problem is that when user enters xyz.com//offer or xyz.com///offer it redirects to xyz.com/offer with 308 code.

I’ve also tried using redirects inside next config:

        return [
            {
                source: '/offer/',
                destination: '/offer',
                statusCode: 301,
            },
        ];
    }

But its impossible to predict all cases with multiple slashes + it doesn’t work as inteded (redirection with 301 doesn’t happen).

Is is any way in next to set all inner redirects to 301?

2

Answers


  1. Update your next.config.js to include a custom server rewrite rule for handling redirects:

    // next.config.js

    module.exports = {
      async rewrites() {
        return [
          // Redirect all routes with multiple slashes to the clean version with 301 status code
          {
            source: '/:path*',
            destination: '/:path*',
            permanent: true,
          },
        ];
      },
    };
    
    Login or Signup to reply.
  2. If you want to stop redirect on 308 then you disable 2 options in your next.config.ts/mjs/js file

    const nextConfig = {
      trailingSlash: false, // MAKE THIS FALSE because this redirect is on 308.
      images: { unoptimized: true },
      reactStrictMode: false,
      cacheMaxMemorySize: 0
      permanent: false, // MAKE THIS OPTION FALSE. FOR REDIRECT
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search