DEV Community

CodeHunterz
CodeHunterz

Posted on

301 Redirects in Next.js: A Migration Checklist for Small Business Sites

Rebuilding a small business website in Next.js is usually a clear upgrade. The new site is faster, easier to maintain, and far more pleasant to work on than the old theme it replaces. But there is one part of a migration that quietly decides whether the client keeps their search traffic or loses it: redirects.

The old site has URLs that Google has indexed for years. Other sites link to them. Customers have them bookmarked. Old flyers and email signatures point to them. When the new site launches with a different URL structure and nothing maps the old paths to the new ones, all of that turns into 404 pages overnight.

This post walks through a practical redirect workflow for Next.js migrations: building the redirect map, implementing it in next.config or middleware, avoiding the common mistakes, and testing everything with a small script before and after launch.

Why redirects matter more than the redesign itself

From a search engine's point of view, a URL is an identity. Ranking signals, backlinks, and history are attached to that exact address. A permanent redirect tells crawlers that the content has moved and that the signals should follow it to the new address.

Without redirects, the new pages start from zero, even if the content is identical. For a local service business that relies on a handful of service and location pages for most of its calls, that can mean weeks or months of lost leads. This is the single most common reason a website redesign hurts rankings, and it is entirely preventable.

Step 1: Build a complete list of old URLs

You cannot redirect what you do not know exists. Before touching the new codebase, collect every URL the old site serves. Use more than one source, because each one misses something:

  • The old XML sitemap. Usually at /sitemap.xml or /sitemap_index.xml on WordPress sites. Save a copy before the old site goes offline.
  • Search Console. The Pages report and the Performance report show URLs Google actually knows about and sends traffic to. Export them.
  • A crawl of the live site. Any crawler will do. This catches pages that were never in the sitemap.
  • Backlink data. Free backlink checkers show which old URLs other sites link to. These are the most valuable ones to preserve.
  • Analytics. Landing page reports reveal old campaign pages and PDFs that still get visits.

Merge everything into one spreadsheet, normalize it (lowercase, no domain, consistent trailing slash), and remove duplicates.

Step 2: Map every old URL to the best new URL

For each old path, pick the single most relevant page on the new site. A few rules keep the map honest:

  • Map like to like. The old /ac-repair-services/ page should point to the new AC repair page, not the homepage.
  • Avoid mass redirects to the homepage. Search engines often treat a redirect to an unrelated page as a soft 404, so the signals do not carry over anyway.
  • Let truly dead pages return 404 or 410. An old blog post about a promotion that ended years ago does not need a redirect if nothing links to it and nothing on the new site replaces it.
  • Merge thin pages thoughtfully. If three old pages about the same service become one strong page, all three can point to it.

Save the final map as JSON in the repo. Version controlling it makes it reviewable in pull requests:

[
  { "from": "/ac-repair-services", "to": "/services/ac-repair" },
  { "from": "/about-us", "to": "/about" },
  { "from": "/blog/2019/05/furnace-tips", "to": "/blog/furnace-maintenance-tips" }
]
Enter fullscreen mode Exit fullscreen mode

Step 3: Implement redirects in next.config

For most small business sites, the built in redirects() function in next.config is the right tool. It runs before the filesystem and routing, works with static and dynamic pages, and is easy to read.

// next.config.mjs
import redirectMap from './redirects.json' with { type: 'json' };

const nextConfig = {
  async redirects() {
    return redirectMap.map(({ from, to }) => ({
      source: from,
      destination: to,
      permanent: true,
    }));
  },
};

export default nextConfig;
Enter fullscreen mode Exit fullscreen mode

A few details worth knowing:

  • permanent: true sends a 308 status, not a 301. Google treats 308 the same way it treats 301 for passing signals, so this is fine. The difference is that 308 preserves the request method, which matters for form posts.
  • Patterns are supported. source: '/blog/:year/:month/:slug' with destination: '/blog/:slug' can replace hundreds of individual rules when the old site used dated blog URLs.
  • Query strings are passed through to the destination by default, which keeps UTM tags on old campaign links intact.

If the old site used a different trailing slash convention than the new one, decide on one style and set trailingSlash accordingly. Next.js will normalize the other form with its own redirect, so you do not need a rule for both /about-us and /about-us/.

Step 4: Use middleware for large or messy maps

Some migrations come with thousands of old URLs, often from an ecommerce platform or a CMS that generated odd paths. Hosting platforms place limits on how many routes a config can hold, and a giant array in next.config gets slow to build and hard to read. In that case, a lookup in middleware is cleaner. (In recent Next.js versions this file is being renamed from middleware.ts to proxy.ts, but the logic is the same.)

// middleware.ts
import { NextResponse, type NextRequest } from 'next/server';
import redirectMap from './redirect-map.json';

const map = redirectMap as Record<string, string>;

export function middleware(request: NextRequest) {
  const raw = request.nextUrl.pathname;
  const path = (raw.length > 1 ? raw.replace(/\/$/, '') : raw).toLowerCase();
  const target = map[path];

  if (target) {
    const url = request.nextUrl.clone();
    url.pathname = target;
    return NextResponse.redirect(url, 308);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!_next|api|favicon.ico|.*\\..*).*)'],
};
Enter fullscreen mode Exit fullscreen mode

Here redirect-map.json is a flat object of { "/old-path": "/new-path" } pairs, which gives constant time lookups. The matcher skips Next.js internals, API routes, and files with extensions so the middleware does not run on every image request.

Lowercasing the incoming path is a small but useful touch. Old WordPress and IIS sites often had mixed case URLs, and backlinks pointing to /About-Us should not break just because the new map is lowercase.

Step 5: Handle the domain level redirects separately

Path redirects are only half of the job. Make sure the host level rules are also in place:

  • HTTP to HTTPS. Most modern hosts do this automatically, but confirm it.
  • One canonical host. Choose either www or the bare domain and redirect the other to it. On Vercel, this is configured on the domain settings, not in code, and it should be a permanent redirect.
  • Old domains. If the business is consolidating a second domain, add it to the project and redirect it to the main host, then let the path rules do the rest.

The goal is that any old URL, on any old host or protocol, reaches its final destination in one hop.

Step 6: Avoid redirect chains and loops

Chains happen when an old URL redirects to another old URL that itself redirects. They are common on sites that have been migrated more than once. Each hop adds latency and some risk that crawlers stop following.

Two habits prevent this:

  1. When you add a new rule, search the existing map for any rule whose destination is the new rule's source, and update it to point straight to the final page.
  2. Never redirect to a URL that is itself in the from column.

A quick sanity check you can run in Node before every deploy:

// scripts/lint-redirects.mjs
import fs from 'node:fs';

const rows = JSON.parse(fs.readFileSync('./redirects.json', 'utf8'));
const sources = new Set(rows.map((r) => r.from));
const problems = rows.filter((r) => sources.has(r.to) || r.from === r.to);

if (problems.length) {
  console.error('Chained or looping redirects:', problems);
  process.exit(1);
}
console.log(`${rows.length} redirects, no chains found`);
Enter fullscreen mode Exit fullscreen mode

Wire it into your CI step so a bad rule never reaches production.

Step 7: Test against the preview deployment

Every redirect should be verified on a real deployment before DNS is switched. Vercel preview URLs are perfect for this. The script below requests each old path without following redirects, checks the status and the Location header, then confirms the destination itself returns 200.

// scripts/check-redirects.mjs
import fs from 'node:fs';

const base = process.argv[2]; // e.g. https://my-preview.vercel.app
const rows = JSON.parse(fs.readFileSync('./redirects.json', 'utf8'));
let failures = 0;

for (const { from, to } of rows) {
  const res = await fetch(base + from, { redirect: 'manual' });
  const location = res.headers.get('location') || '';
  const finalPath = location ? new URL(location, base).pathname : '';
  const okRedirect = [301, 308].includes(res.status) && finalPath === to;

  const dest = await fetch(base + to, { redirect: 'manual' });
  const okDest = dest.status === 200;

  if (!okRedirect || !okDest) {
    failures++;
    console.log(`FAIL ${from} -> ${res.status} ${location} (dest ${dest.status})`);
  }
}

console.log(failures ? `${failures} failures` : 'All redirects OK');
process.exit(failures ? 1 : 0);
Enter fullscreen mode Exit fullscreen mode

Run it with node scripts/check-redirects.mjs https://your-preview-url. Run it again against the production domain right after launch, because host level rules only apply there.

For spot checks without code, curl -I https://example.com/old-path shows the status and Location header in one line, and a free website checker can confirm the final page loads over HTTPS with the right meta tags.

Step 8: Clean up after launch

Redirects keep old links working, but the new site should not depend on them internally.

  • Update internal links to point straight at the new URLs. Every internal link that goes through a redirect is a wasted hop.
  • Regenerate the sitemap so it only lists final, 200 status URLs. Submit it in Search Console.
  • Update canonical tags so each page references its own new URL, not the old one.
  • Watch the 404 report for a few weeks. Search Console and server logs will surface old URLs you missed. Add them to the map as they appear.
  • Keep the redirects in place. Google recommends keeping them for at least a year, and there is rarely a good reason to remove them at all. They cost almost nothing to maintain.

A short pre launch checklist

  • Old URL inventory collected from sitemap, Search Console, crawl, backlinks, and analytics
  • Every valuable old URL mapped to its closest new page
  • Redirects implemented as permanent (301 or 308)
  • No chains, no loops, no mass redirects to the homepage
  • Host level rules for HTTPS and www confirmed
  • Redirect test script passing on preview and production
  • Internal links, sitemap, and canonicals updated
  • 404 monitoring scheduled for the first month

Wrapping up

Redirects are not glamorous, and they rarely make it into the project proposal. But on a migration they are the difference between a new site that inherits years of search history and one that starts from scratch. Treat the redirect map as a first class artifact in the repo, test it like code, and the launch becomes a non event for rankings.

If you are planning a move to Next.js and want a second pair of eyes on the migration plan, our team does this work as part of Next.js development projects, and a free website audit is a good way to see which old pages carry the most value before you start.

CodeHunterz Team

Top comments (0)