WordPress to Next.js Static Migration Without Losing Rankings (Spec, .htaccess & 11 Real Fixes)

By Rohan Babbar6 min read
WordPress to Next.js Static Migration Without Losing Rankings (Spec, .htaccess & 11 Real Fixes)

Most WordPress-to-Next.js migrations don't lose organic traffic because Google dislikes static sites. They lose traffic because URLs silently change status codes, query-string archives return 404s, CDNs cache missing images during upload, or someone "improves" titles on pages that were already ranking.

A clean local build proves nothing. After migrating my own portfolio and high-traffic client sites from WordPress to static Next.js exports on shared hosting, I stopped trusting manual checklists and moved every SEO rule into a spec file, a generated .htaccess, automated build guards, and a two-pass deploy.

Below is the exact architecture and the 11 production failures that forced each guardrail into place.

1. Never touch code before locking a one-row-per-URL spec

Crawl the live WordPress site first — including sitemaps, Search Console's top URLs, redirect chains, and query-string archives (?p=, ?page_id=, ?cat=, ?tag=, ?author=). On a mature WordPress site, it's common to uncover over a thousand URLs and hundreds of legacy redirect hops.

Every single discovered URL gets one explicit disposition in a single spec file:

  • 200 — keep live at the exact same slug and trailing-slash pattern.
  • 301 — consolidate cleanly to its single canonical destination (no chains, no loops).
  • 410 — intentionally gone junk/spam URLs.
  • 404 — genuine dead paths handled by a real static 404.html.

Alongside the status code, lock robots, canonical, and in_sitemap per URL. Hard rule: never rewrite copy, H1s, or title tags on pages that already rank or convert during a migration. Change the infrastructure first; optimise copy only after post-launch stability is confirmed in Search Console.

2. Compile .htaccess from the spec (and fail on conflicts)

Hand-editing Apache/LiteSpeed .htaccess rules is where redirect loops are born. Instead, compile .htaccess directly from the URL spec with a build script that exits non-zero if it detects:

  • Two rules targeting the same source path.
  • A redirect loop or multi-hop chain (A → B → C).
  • Any live URL missing from the spec.

Order matters inside .htaccess:

RewriteEngine On

# 1. Explicit 301s and query-string redirects BEFORE host/slash normalisation
RewriteCond %{QUERY_STRING} (^|&)p=([0-9]+)(&|$)
RewriteRule ^$ /blogs/? [R=301,L]

# 2. Force HTTPS + canonical non-www host
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

# 3. Consolidated categories & legacy WordPress slugs
RewriteRule ^category/old-slug/?$ /category/canonical-slug/ [R=301,L]
RewriteRule ^(sitemap_index\.xml|post-sitemap\.xml)$ /sitemap.xml [R=301,L]

# 4. Intentional removals return 410 Gone
RewriteRule ^legacy-junk-path/?$ - [G,L]

# 5. Enforce trailing slashes to match WordPress
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-z0-9]+|/)$ [NC]
RewriteRule ^(.*)$ /$1/ [R=301,L]

Configure next.config.mjs with output: 'export', trailingSlash: true, and images: { unoptimized: true }, and run a pre-build media pipeline that generates lossless WebP + responsive variants while preserving original image filenames and URLs.

3. Enforce pre-build SEO guards before next build finishes

Every commit runs an automated pre-build gate that fails CI if any rule breaks:

  • Every 200 URL in the spec exists in the built static output (out/).
  • Every page has exactly one <h1>, a non-empty <title>, <meta name="description">, and a self-referencing canonical URL.
  • Zero broken internal links across all markdown posts and pages.
  • sitemap.xml matches the spec's indexable 200 URLs exactly (excluding any noindex pages).
  • No forbidden third-party/injected affiliate domains survive from legacy WordPress database imports.

4. Deploy in two passes with lftp (media first, HTML second)

Standard FTP deploy actions frequently fail on harmless cleanup permissions or upload HTML pages before their new cover images exist — causing the CDN to cache a 404 for the image.

My GitHub Actions deploy workflow runs lftp mirror --reverse --no-perms (with retries, never deleting existing server files, and skipping legacy wp-content/ uploads) in two explicit passes:

  1. Pass 1: Upload everything except *.html and *.txt (images, CSS, JS, fonts, WebP variants).
  2. Pass 2: Upload *.html, sitemap.xml, and robots.txt only after every static asset is live on origin.

After the workflow finishes, verify the live site in an incognito window by checking the actual deployed CSS hash and response headers — a green GitHub Actions tick is not proof that the right folder went live.

5. Eleven real migration bugs I hit (and how each was fixed)

Failure hit in production Cause Permanent fix
1. 403 Forbidden after zip upload Uploaded archive extracted with 0600 file permissions on shared hosting Switched to lftp --no-perms over GitHub Actions
2. Green deploy, zero live change Relative FTP target path deployed into a sibling directory instead of public_html Locked exact server root path and verified live CSS hash post-deploy
3. CDN cached a 404 on a new cover image HTML went live seconds before the image finished uploading Split upload into two-pass deploy (assets first, HTML second)
4. Live 404 right after building locally Local commit stayed unpushed (ahead 1), so Actions deployed the previous commit Mandatory git status -sb check confirming master matches origin/master before triggering deploy
5. Two consecutive failed deploys on a new post New image paths weren't registered in the build guard's asset list Wired build guard directly to disk + prepare-media manifest
6. Sticky header broke across browsers overflow-x: hidden on the page wrapper disabled position: sticky Replaced with overflow-x: clip
7. Old WordPress cache kept serving stale homepage Hosting/CDN page cache held the previous WP HTML after switch-over Explicit cache purge + ExpiresByType text/html "access plus 0 seconds" in .htaccess
8. Broken legacy images after WordPress removal wp-content/uploads moved out alongside old WordPress core files Kept /wp-content/ preserved on server and excluded from mirror deletes
9. Malformed WP import artefacts Decorative icons rendered full-width; teaser blocks paired one post's title with another's image Cleaned markdown import scripts + added automated visual checks
10. Injected third-party links hidden in old posts Legacy WordPress content carried stale outbound affiliate links Stripped during import and added a forbidden-domain check to CI
11. Shared hosting inode ceiling (~80%) Keeping full old WordPress backup directories inside the same hosting account Archive old WP files off-server after verifying backups

6. Post-launch verification & AI-search readiness

Once live HTTP status codes match the spec:

  • Submit the new sitemap.xml in Google Search Console and Bing Webmaster Tools.
  • Verify robots.txt explicitly allows search and AI crawlers, and keep Article, BreadcrumbList, and matching FAQPage JSON-LD rendered directly in static HTML (no client-side JS required to read content).
  • Track daily target-market non-brand clicks alongside URL Inspection status so you immediately separate genuine ranking shifts from normal crawl-rate noise — see connecting Google Search Console to Claude and Search Console clicks and impressions by country.

How this applies across industries

Industry Highest-risk migration asset Guardrail that protects revenue
E-commerce Category filters, pagination & high-converting product slugs Spec-locked 301 map + zero copy changes on top revenue pages
B2B Comparison pages, whitepapers & UTM-tagged landing pages Preserve query strings across redirects + verify GA4/CRM events live
Education Program syllabus URLs & multi-year intake pages 301 outdated intake URLs to canonical evergreen program pages
Services & Local City/service landing pages & consultation forms Lock trailing slashes, schema parity, and live enquiry_click firing

For how I guard automated data pipelines with the same zero-regression mindset, see self-refreshing marketing dashboards with GitHub Actions or view all systems I've built.

FAQ

Will migrating from WordPress to Next.js hurt SEO rankings?

Not if you preserve URL slugs, trailing slashes, internal links, metadata, structured data and 301 redirects cleanly. Traffic drops almost always come from unmapped URLs, accidental noindex tags, or rewriting ranking page titles during the move.

Can you host a Next.js site on shared hosting without a Node server?

Yes. Configuring output: 'export' in next.config.mjs compiles the site into pure static HTML, CSS, JS and assets that run directly on Apache or LiteSpeed shared hosting with .htaccess redirects and CDN caching.

Why use a two-pass FTP/lftp deploy instead of a single upload?

Uploading HTML before new images and CSS finish transferring allows the CDN to cache a 404 for missing assets. Uploading media and bundles in Pass 1 and HTML in Pass 2 eliminates CDN 404 caching.

Should I rewrite titles and content during a site migration?

No. Keep titles, H1s and copy unchanged on pages that already rank or convert so you isolate infrastructure variables. Run copy and CTR experiments only after post-migration indexing and rankings stabilise.


Planning a WordPress migration or technical SEO rebuild without risking existing organic revenue? See my SEO consulting work, message me on LinkedIn, or email rohan.sgtb@gmail.com.

next.jswordpress migrationtechnical seohtaccessgithub actions
ShareLinkedInX
Rohan Babbar
Rohan Babbar

Digital Marketing Manager — paid media, SEO and marketing systems. Connect on LinkedIn · rohan.sgtb@gmail.com