Redirects when replacing a website: build the map, test it, keep it
How to keep your search traffic when you relaunch a site: list the old URLs, write one-to-one redirects, test the edge cases, and check the map with a script.
· 8 min read
- SEO
- Redirects
- Cloudflare
When you replace a website, the old URLs do not go away. They sit in Google’s index, in other people’s links, in bookmarks and in email signatures. If the new site answers them with a 404, the traffic and the reputation attached to them are lost.
The fix is a redirect map: a list saying that each old address now lives at a particular new address. Writing it is not hard. Getting it right is mostly a matter of being thorough, and then testing the unglamorous details: trailing slashes, query strings, and redirects that point at other redirects.
The behaviour described below was tested on the local Workers runtime (the one wrangler dev starts) serving a static build with a _redirects file, which is how this site is hosted, with html_handling set to drop-trailing-slash and not_found_handling set to 404-page. Other servers differ in the details, so run the same checks against yours.
Step 1: list every old URL that matters
Start with what search engines and people actually use, not what you remember building:
- The old sitemap, if there was one.
- The pages report and the links report in Google Search Console, which show what is indexed and what other sites link to.
- Your analytics: landing pages from the last year or so.
- A crawl of the old site, before you switch it off.
Merge them into one file, one URL per line. Strip the domain, keep the path. Then give each old URL one of three fates:
- A close equivalent exists on the new site. Redirect to it.
- The content has moved, merged or been replaced. Redirect to the page that now covers it.
- There is no equivalent. Let it return 404, or 410 if the removal is deliberate.
The third option is a legitimate answer, and people avoid it. Sending every dead URL to the home page looks tidy but does not help anyone. Search Engine Roundtable reported Google’s John Mueller saying that Google sees redirecting every page to the home page as a soft 404, and a visitor who lands on the home page when they wanted a specific article is not well served either. Redirect only where the destination answers what the old page answered.
Step 2: write the rules, one to one
Use a permanent redirect, status 301, since you are telling search engines the move is for good. Redirect each old page to its direct replacement, not to a generic section page.
On a Cloudflare Workers static site, redirects go in a _redirects file in the build output, one rule per line: source, destination, status.
/about-us /about 301
/about-us/ /about 301
/our-work.html /case-studies 301
/news/:slug /blog/:slug 301
/products/* /services/:splat 301
Write destinations in the slash form your site serves, or the host adds a hidden second hop. Cloudflare’s documentation sets a limit of 2,000 static rules and 100 dynamic rules (those with placeholders or splats) per file, and 1,000 characters per rule. A small business site will not get near that. If yours does, Cloudflare’s Bulk Redirects feature is the documented route for larger lists.
What matched in our tests
These are the results that catch people out. Each was a request to the local runtime, checking the status and Location header, with only the rule shown in the file. The 404s are for old URLs with no matching file on the site. Pages that do exist on the new site are tidied by the host itself: /about/ and /about.html get an automatic redirect to /about under this configuration.
| Rule | Request | Result |
|---|---|---|
/old-about /about |
/old-about |
301 to /about |
/old-about /about |
/old-about/ |
404 |
/old-about /about |
/OLD-ABOUT |
404 |
/old-about /about |
/old-about.html |
404 |
/old-about /about |
/old-about?utm=1 |
301 to /about?utm=1 |
/blog/:slug /articles/:slug |
/blog/a/b |
404 |
/blog/:slug /articles/:slug |
/blog/a/ |
404 |
/shop/* /store/:splat |
/shop/x/ |
301 to /store/x/ |
/shop/* /store/:splat |
/shop |
404 |
The lessons:
- Matching is exact. Case, a trailing slash and a
.htmlextension all count. If the old site answered at/about-us,/about-us/and/about-us.html, you need a rule for each form that was ever linked to. The old URL list from Search Console will show which forms are in use. - Placeholders match one path segment.
:slugdoes not matcha/b. Use a splat (*) for anything with depth. - A splat does not match its own prefix.
/shop/*handled/shop/and/shop/x, but not/shop. Add the bare path as its own rule. - Query strings travel with the redirect.
?utm=1was carried over to the new address, which is usually what you want, as it keeps campaign tags intact. - Do not put a query string in the source. We tried a rule with
?q=:qin the source. The runtime ignored the query part, so the rule matched/searchwith or without a query and left the unresolved:qin the destination. If old URLs identify pages by query string (/page.php?id=12), a static_redirectsfile is the wrong tool. Handle those in a Worker, where you can read the parameters. - The first rule wins. With two rules for the same source, the earlier one applied. Wrangler ignored the later one and logged a warning.
Step 3: no chains, no loops
The server does not follow a redirect to its end, at least on the host we tested. If /a redirects to /b, and /b redirects to /c, a request for /a returns a 301 to /b, and the client then has to ask again. We confirmed it: the response to /a pointed at /b, not /c.
Chains happen naturally. A site gets redesigned in 2022 and redirects are added. It is redesigned again and a new set is added on top, pointing at pages that are now themselves redirected. Each hop is another round trip for visitors and crawlers alike, and chains are easy to break later by editing one link. The map should be flat: every old URL points directly at a live page.
Do not rely on remembering this. Check it with a script. This one reads the static rules, flags duplicates, non-301 statuses, chains and loops, and checks that each destination is a file the build actually produced. Run it as node check-redirects.mjs dist old-urls.txt:
import { readFileSync, existsSync } from "node:fs";
import { join } from "node:path";
const [dist, oldUrlsFile] = process.argv.slice(2);
const rules = new Map(); // source -> { to, status, line }
const problems = [];
if (!existsSync(join(dist, "_redirects"))) {
console.log(`no _redirects file in ${dist}`);
process.exit(1);
}
readFileSync(join(dist, "_redirects"), "utf8").split("\n").forEach((raw, i) => {
const text = raw.trim();
if (!text || text.startsWith("#")) return;
const [from, to, status = "301"] = text.split(/\s+/);
if (!to) return void problems.push(`line ${i + 1}: expected a source and a destination`);
if (from.includes("*") || from.includes(":")) return; // only static rules here
if (rules.has(from)) problems.push(`line ${i + 1}: duplicate source ${from} (first rule wins)`);
else rules.set(from, { to, status, line: i + 1 });
});
// "Live" means the new build serves it: a file, <path>.html or <path>/index.html.
const live = (p) => {
const path = p.split(/[?#]/)[0].replace(/\/$/, "") || "/index";
return [path, `${path}.html`, `${path}/index.html`].some((f) => existsSync(join(dist, f)));
};
for (const [from, { to, status, line }] of rules) {
if (!["301", "308"].includes(status)) problems.push(`line ${line}: ${from} uses ${status}, expected 301`);
const seen = [from];
const path = (t) => t.split(/[?#]/)[0]; // rules match the path only
let next = to;
while (rules.has(path(next)) && !seen.includes(path(next))) {
seen.push(path(next));
next = rules.get(path(next)).to;
}
if (seen.includes(path(next))) problems.push(`line ${line}: loop ${[...seen, next].join(" -> ")}`);
else {
if (seen.length > 1) problems.push(`line ${line}: chain ${seen.join(" -> ")} -> ${next}; point ${from} at ${next}`);
if (!/^(https?:)?\/\//.test(next) && !live(next)) problems.push(`line ${line}: ${next} is not served by the new site`);
}
}
if (oldUrlsFile) {
for (const url of readFileSync(oldUrlsFile, "utf8").split("\n").filter(Boolean)) {
const path = new URL(url, "https://example.com").pathname;
if (!rules.has(path) && !live(path)) problems.push(`no redirect and no page for ${path}`);
}
}
console.log(problems.length ? problems.join("\n") : "ok");
process.exit(problems.length ? 1 : 0);
Given rules where /a goes to /b and /b goes to /about, it prints line 1: chain /a -> /b -> /about; point /a at /about. The final loop over the old URL list is the important one. It tells you which old addresses would return a 404 on the new site, and each is either a missing rule or a decision to let it go. Because the script compares exact paths, include the trailing-slash and .html variants in your list, or it will not notice them.
Run it in your build or CI, so a later edit cannot quietly break the map. Dynamic rules (placeholders and splats) are skipped, so test those by hand with curl.
Step 4: test the live site
After deploying, request a sample of old URLs and read the status and destination, without following the redirect:
curl -s -o /dev/null -w "%{http_code} %{redirect_url}\n" https://example.com/about-us/
You want 301 and the final address, in one hop. Check the awkward cases from the table above, a few URLs with query strings, and one that should 404. Then submit the new sitemap in Search Console and watch the pages report over the following weeks. Pages showing as “Page with redirect” under the old URLs are normal. Old URLs reported as “Not found (404)” that you meant to redirect are the ones to fix.
Step 5: keep the redirects
Do not remove the rules after a month. Google’s advice for site moves, as reported by Search Engine Journal, is to keep redirects in place for at least a year, and links from other sites do not stop pointing at the old address because you have moved. The cost of a redirect is a line in a text file. Keep them for as long as the old URLs still receive any traffic, and in practice, for good.
A short checklist
- Build the old URL list from the sitemap, Search Console, analytics and a crawl.
- Give each URL a destination, or decide to let it 404.
- Write 301 rules to the direct replacement, including trailing-slash and
.htmlforms. - Run a script to catch chains, loops, duplicates and dead destinations.
- Test old URLs against the deployed site, not just the config.
- Leave the rules in place.
We plan and carry out site migrations as part of our web development work, including the redirect map and the checks around it. If you are replacing a site and want to keep what it has earned, get in touch.