Dev.to WebDev 🛠 Dev 👁 0 📖 5 min read

Moving from WordPress to Next.js without losing rankings: the redirect routine

Moving a business site from WordPress to Next.js is usually a good trade: faster pages, a cleaner codebase and fewer plugin updates. The part that goes wrong is not the build. It is the old URLs. Google has years of sign

Moving a business site from WordPress to Next.js is usually a good trade: faster pages, a cleaner codebase and fewer plugin updates. The part that goes wrong is not the build. It is the old URLs. Google has years of signals attached to /services/plumbing-repairs/ and /2021/04/how-much-does-a-boiler-cost/, and if those paths start returning 404 on launch day, the rankings and the backlinks pointing at them go with them.

This walkthrough is the redirect routine we use: export every old URL, build a redirect map, decide what to do about trailing slashes, and test every line before the DNS switch.

1. Export every old URL before you touch anything

Do this while the WordPress site is still live. You want three lists, merged and de-duplicated:

  • The XML sitemap. WordPress has shipped a core sitemap at /wp-sitemap.xml since version 5.5. If Yoast or Rank Math is active, theirs is usually at /sitemap_index.xml. Each is an index that points to per-type sitemaps (posts, pages, categories).
  • Google Search Console. Performance → Pages, last 16 months, export. This catches URLs that get impressions but were dropped from the sitemap, such as old tag archives.
  • Your backlink tool or Search Console Links report. Any URL other sites link to must keep working, even if it no longer appears in the sitemap.

A short Node script pulls the sitemap side for you:

// list-urls.mjs  (Node 18+, uses the built-in fetch)
const start = process.argv[2]; // e.g. https://example.com/wp-sitemap.xml
const seen = new Set();

async function walk(url) {
  const xml = await (await fetch(url)).text();
  const locs = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map(m => m[1].trim());
  for (const loc of locs) {
    if (loc.endsWith('.xml')) await walk(loc);   // a child sitemap
    else seen.add(new URL(loc).pathname);
  }
}

await walk(start);
console.log([...seen].sort().join('\n'));

Run node list-urls.mjs https://example.com/wp-sitemap.xml > old-urls.txt, then paste in the Search Console and backlink lists and sort them again.

2. Build the redirect map

Put the map in a plain file the client can read, one old path and one new path per row:

/services/plumbing-repairs/,/services/plumbing
/2021/04/how-much-does-a-boiler-cost/,/guides/boiler-cost
/category/news/,/blog
/?p=482,/guides/boiler-cost

Rules we follow:

  • Map to the closest equivalent page, not to the homepage. Google treats a mass redirect to the homepage much like a 404.
  • Keep the slug when the content is the same. If /about/ becomes /about, that is a trailing-slash question (step 3), not a redirect row.
  • Do not chain. Every old URL should reach its final page in one hop.

Then load the file in next.config.mjs:

// next.config.mjs
import fs from 'node:fs';

const rows = fs.readFileSync('./redirects.csv', 'utf8')
  .split('\n').map(l => l.trim()).filter(Boolean)
  .map(l => l.split(','));

export default {
  async redirects() {
    return rows.map(([source, destination]) => ({
      source,
      destination,
      permanent: true, // Next.js answers permanent redirects with a 308
    }));
  },
};

Two details from the Next.js docs are worth knowing. First, permanent: true sends a 308, not a 301; search engines treat both as permanent. Second, source matches the path, so query-string URLs like /?p=482 need the has option with a query condition rather than a plain row:

{ source: '/', has: [{ type: 'query', key: 'p', value: '482' }],
  destination: '/guides/boiler-cost', permanent: true }

For very large maps (the docs mention moving to Middleware once you are into the thousands), read the CSV into a Map in middleware.js and return NextResponse.redirect(new URL(target, request.url), 308) when the path matches.

3. Decide on trailing slashes once

WordPress URLs end in a slash by default (/about/). Next.js defaults to no trailing slash and redirects /about/ to /about for you. Both work, but you have to pick one:

  • Keep the slashes: set trailingSlash: true in next.config.mjs. Old URLs then resolve directly, and you only need redirect rows for paths that really changed. This is the lowest-risk option for a migration.
  • Drop the slashes: keep the default. Every old URL now takes one automatic redirect hop, and any row in your map must use the slash-less destination so you do not create a chain (/about/ → /about → /about-us).

Whichever you pick, make the canonical tags, the sitemap and internal links use the same form.

4. Test every URL before launch

Run the whole old-URL list against the staging build. The script below prints anything that is not a single redirect to a 200:

// check-redirects.mjs
import fs from 'node:fs';
const base = process.argv[2]; // e.g. https://staging.example.com
const paths = fs.readFileSync('old-urls.txt', 'utf8').split('\n').filter(Boolean);

for (const p of paths) {
  const first = await fetch(base + p, { redirect: 'manual' });
  if (first.status === 200) continue;                    // path kept as is
  const loc = first.headers.get('location');
  if (![301, 308].includes(first.status) || !loc) {
    console.log('BROKEN', first.status, p); continue;
  }
  const second = await fetch(new URL(loc, base), { redirect: 'manual' });
  if (second.status !== 200) console.log('CHAIN/404', p, '->', loc, second.status);
}

Fix every line it prints, run it again until it prints nothing, then repeat it against production straight after launch. For spot checks, curl -I https://example.com/old-path/ shows the status and the location header.

After launch

  • Submit the new sitemap in Search Console and watch Pages → Not found (404) for two to four weeks.
  • Keep the redirects in place for at least a year; there is no SEO benefit in removing them early.
  • Ask the owners of your most valuable backlinks to update the URL where they can.

FAQ

Do 308 redirects pass ranking signals like 301s?
Yes. Google treats 301 and 308 as permanent redirects.

Can I redirect everything to the homepage to save time?
You can, but Google usually treats those as soft 404s, so the old pages' value is lost.

Should the redirects live in Next.js or at the CDN?
Either works. next.config keeps them in the repo next to the code; a CDN rule list is handy if the marketing team needs to edit them without a deploy.

If you are planning a WordPress to Next.js move and want a second pair of eyes on the redirect map, our Next.js development team at Dzimark runs this routine on every migration.

Sources: Next.js docs (redirects, trailingSlash, Middleware); WordPress 5.5 release notes (core XML sitemaps); Google Search Central (redirects and Google Search).

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.