Redirect Map Builder for Big Site Migrations
Matching thousands of old URLs to the right new pages by hand takes weeks, and mistakes cost traffic. This prompt builds your redirect map with smart rules, pattern matching and AI-assisted content matching, plus the safety checks that stop loops, chains and bad matches.
Example input
This is exactly what we gave the model. You replace it with your own details.
- Old site and new site: https://blog.example.org -> https://www.example.org/learn/ - Number of old URLs to map: About 3,800 old blog URLs (posts, tags, categories, author pages) - Old URL list (CSV with URL, title, category, clicks, backlinks if available): url,title,category,clicks_90d,backlinks /2021/03/how-to-start-a-vegetable-garden/,How to Start a Vegetable Garden,Vegetables,8200,41 /2021/05/best-tomato-varieties-for-beginners/,Best Tomato Varieties for Beginners,Vegetables,3100,12 /2022/02/composting-101/,Composting 101,Soil,2600,19 /2022/07/why-are-my-tomato-leaves-turning-yellow/,Why Are My Tomato Leaves Turning Yellow?,Vegetables,4700,8 /tag/tomatoes/,Tomatoes,,40,0 /author/sam/,Sam,,5,0 /2020/11/garden-gift-guide-2020/,Garden Gift Guide 2020,Gifts,30,2 (3,793 more rows in the full file) - New URL list (CSV with URL, title, category): url,title,category /learn/vegetables/start-a-vegetable-garden/,How to Start a Vegetable Garden,Vegetables /learn/vegetables/tomato-varieties/,The Best Tomato Varieties to Grow,Vegetables /learn/soil/composting/,Composting: A Complete Beginner's Guide,Soil /learn/vegetables/yellow-tomato-leaves/,Yellow Tomato Leaves: Causes and Fixes,Vegetables /learn/vegetables/,Vegetables, (about 1,400 rows; many old posts were merged) - URL structure changes: /YYYY/MM/post-slug/ becomes /learn/[category]/[shorter-slug]/; tag and author pages are removed; old gift guides are not kept - Where redirects will live: Cloudflare Bulk Redirects for the old subdomain - My skills: Spreadsheets and a little Python (I can run a script someone gives me)
Real output
Pasted straight from the model. We did not fix a word.
Quick questions (I've carried on with my best guess for each, so correct me if one is wrong)
- Will the old blog server be switched off after launch? Guess: yes. Then Cloudflare has to answer every
blog.example.orgrequest by itself, so I've added a small Worker that returns 410 or 404 for anything that isn't redirected. - Is the old blog WordPress-style, with categories at
/category/[name]/and extra versions like/post-slug/amp/and/post-slug/feed/? Guess: yes. - Do the old category names match the new ones (Vegetables →
/learn/vegetables/, Soil →/learn/soil/)? Guess: mostly yes. For any that don't, the script reads an optional mapping file. - What counts as "high traffic" for the review you require? Guess: 500+ clicks in 90 days or 5+ backlinks.
- Are all ~1,400 new URLs live and returning 200 at exactly the URLs in your new list (with trailing slashes)? Guess: they will be live before the redirects go on.
1. Process steps for your skill level
You'll use Python for the matching and your spreadsheet for the review. You run three commands. Everything else happens in the sheet.
How the script follows your method
- Step 1 (safest first): it tries an exact title match first, then a "shorter slug" rule: every key word in the new slug must appear in the old slug, and both pages must be in the same category. On your sample, these two rules alone match all 4 posts (for example,
best-tomato-varieties-for-beginners→tomato-varieties). - Step 2 (match by meaning): a free local model turns each title into a text embedding. The script then finds the nearest new title, inside the same category first. Your new URLs have no dates, so it filters by category, not year. The year is only used to spot dated posts like the 2020 gift guide.
- Step 3 (safety): a target must be a live page from your new list. It can't be the homepage, and it can't be the old URL itself.
- Step 4 (review): the sheet is sorted by value, using clicks_90d + 100 × backlinks. The 100 is my guess at the weight of one backlink.
A. Prepare (about 30 minutes)
- Make one folder containing
map_redirects.py(section 3),old_urls.csv(all ~3,800 rows) andnew_urls.csv(all ~1,400 rows). Keep the column names you already use. - Make
tag_map.csvwith the columnsold_url,new_url. Filter your old list to the/tag/rows that have clicks or backlinks above 0. Add a row only when a hub truly fits, e.g./tag/tomatoes/,/learn/vegetables/. Every other tag gets a 410 automatically. - Only if some old category names differ from the new ones, make
category_map.csvwith the columnsold_category,new_hub(e.g.Veg Patch,/learn/vegetables/).
B. Small batch first, then the full set
- Install once:
pip install pandas sentence-transformers - Test run:
python map_redirects.py map --limit 50. This maps your 50 most valuable URLs intomapping.csv. The first run downloads a model of about 90 MB. - Check those 50 rows yourself. If good matches get scores that are too low, lower
GOOD_SCOREa little. If wrong matches score high, raise it. Then deletemapping.csvbut keep thecache_*files, because they make re-runs fast. - Full run:
python map_redirects.py map. It saves every 500 rows. If it stops, run the same command again and it picks up where it left off.
C. Review in your spreadsheet
- Open
mapping.csvand filter toneeds_review = YES. The rows are already in priority order, so start at the top. - In the
decisioncolumn, write one of three things:OKto accept, a different new URL, or410. Thesecond_bestcolumn shows the runner-up so you don't have to search for it. - Helper formulas. Put your new URL list in a tab called
new, with the paths in column A:- Is the target live?
=IF(B2="","",IF(COUNTIF(new!A:A,SUBSTITUTE(B2,"https://www.example.org",""))>0,"ok","NOT IN NEW LIST")) - How many old URLs point here?
=IF(B2="","",COUNTIF(B:B,B2)) - Is the URL you typed in the decision column real?
=IF(OR(K2="",K2="OK",K2="410"),"",IF(COUNTIF(new!A:A,SUBSTITUTE(K2,"https://www.example.org",""))>0,"ok","CHECK"))
- Is the target live?
- Spot-check 50 random rows marked
needs_review = NO. If more than 2 are wrong, raiseGOOD_SCOREand run again (this error limit is a guess at what's acceptable). - Save the sheet as CSV with the name
mapping_reviewed.csv.
D. Export and launch
- Run
python map_redirects.py export. It writescloudflare_bulk_redirects.csv,gone_410.txtandexport_problems.txt. Fix every problem and export again until it reports 0 blocked rows and 0 pending reviews. - Upload a 20–30 row test list to Cloudflare first, then the full list (section 5).
- After launch, run
python qa_check.py(section 5).
2. Pattern rules (Cloudflare Bulk Redirects format)
Cloudflare Bulk Redirects are static URL-to-URL lists with no wildcards or regex. They also can't work out [category] or [shorter-slug] from /YYYY/MM/post-slug/. So the script applies the pattern rules, and Cloudflare receives one row per old URL.
# Rules the script applies, in this order
R1 Blog home / -> /learn/
R2 Post, same title /YYYY/MM/{slug}/ -> new page with the identical title
R3 Post, short slug /YYYY/MM/{old-slug}/ -> /learn/{cat}/{new-slug}/
when every key word of new-slug is in old-slug, and {cat} = the post's category
e.g. why-are-my-tomato-leaves-turning-yellow -> yellow-tomato-leaves
R4 Post, meaning anything R2/R3 missed -> nearest new page by embeddings (same category first)
R5 Category /category/{cat}/ (+ /page/N/) -> /learn/{cat}/ only if that hub exists
R6 Tag /tag/{tag}/ -> hub from tag_map.csv only, otherwise 410
R7 Removed (410) /author/*, gift guides (slug has "gift-guide" or category = Gifts),
date archives /YYYY/ and /YYYY/MM/, posts with no good match
R8 Variants /{path} (no slash), /{path}/amp/, /{path}/feed/, /{path}/comment-page-2/
-> same target as /{path}/, still one hop
NEVER a target of https://www.example.org/ (homepage): the script blocks it
Upload file format. No header row. The columns are: source, target, status, preserve query string, include subdomains, subpath matching, preserve path suffix.
blog.example.org/,https://www.example.org/learn/,301,FALSE,FALSE,FALSE,FALSE
blog.example.org/2021/03/how-to-start-a-vegetable-garden/,https://www.example.org/learn/vegetables/start-a-vegetable-garden/,301,FALSE,FALSE,TRUE,FALSE
blog.example.org/2021/03/how-to-start-a-vegetable-garden,https://www.example.org/learn/vegetables/start-a-vegetable-garden/,301,FALSE,FALSE,FALSE,FALSE
blog.example.org/2022/02/composting-101/,https://www.example.org/learn/soil/composting/,301,FALSE,FALSE,TRUE,FALSE
blog.example.org/2022/02/composting-101,https://www.example.org/learn/soil/composting/,301,FALSE,FALSE,FALSE,FALSE
blog.example.org/tag/tomatoes/,https://www.example.org/learn/vegetables/,301,FALSE,FALSE,TRUE,FALSE
blog.example.org/tag/tomatoes,https://www.example.org/learn/vegetables/,301,FALSE,FALSE,FALSE,FALSE
What the columns are doing:
- Two rows per URL (with and without the trailing slash). This keeps every redirect to one hop. A separate "add a slash" rule would create a 2-hop chain.
- Subpath matching = TRUE on the slash version. It catches
/amp/,/feed/,/comment-page-2/and attachment URLs under each post. The script turns it off for/and for any URL that has another listed URL beneath it, so nothing gets swallowed by a wider match. - Preserve query string = FALSE. This drops
?utm_…and WordPress leftovers like?replytocom=. Set it to TRUE if you want UTM tags from old newsletters to carry through.
Cloudflare setup
- DNS: keep
blogproxied (orange cloud). If the old server goes off, pointblogatAAAA 100::(proxied). This is Cloudflare's usual placeholder for a hostname with no origin server. - Bulk Redirects → create a list: name it
blog_to_learn, choose type Redirect, and uploadcloudflare_bulk_redirects.csv. The export prints the row count (about 2 per redirected URL), so check it fits your plan's Bulk Redirects limit. - Create a Bulk Redirect rule that uses the list. Cloudflare writes the expression for you:
http.request.full_uri in $blog_to_learn. - Catch-all Worker on route
blog.example.org/*. Bulk Redirects run before Workers, so this only sees URLs that were not redirected. It returns 410 for deliberate removals and 404 for everything else. That split lets your weekly 404 check show only the URLs you missed:
// Cloudflare Worker - route: blog.example.org/*
const GONE = new Set([
// paste the lines of gone_410.txt here, e.g.
"/author/sam/",
"/2020/11/garden-gift-guide-2020/",
]);
const GONE_PREFIXES = ["/tag/", "/author/"];
export default {
async fetch(request) {
let path = new URL(request.url).pathname.toLowerCase();
if (!path.endsWith("/")) path += "/";
const gone = GONE.has(path) || GONE_PREFIXES.some((p) => path.startsWith(p));
const status = gone ? 410 : 404;
const html = `<!doctype html><title>${status}</title>
<p>This page is no longer here. Browse our guides at
<a href="https://www.example.org/learn/">www.example.org/learn/</a>.</p>`;
return new Response(html, { status, headers: { "content-type": "text/html; charset=utf-8" } });
},
};
This setup also gives /robots.txt on the old subdomain a 404, which Google reads as "crawl everything". Google needs to crawl the old URLs to see the redirects, so don't block it.
Three Cloudflare details I'm fairly sure about but haven't checked for your account. Confirm them in your 20-row test: the CSV needs no header row; sources without https:// match both http and https; and a request with ?utm_source=… still matches its source row.
3. Python script
Save this as map_redirects.py:
#!/usr/bin/env python3
"""
map_redirects.py - builds the 301 map blog.example.org -> www.example.org/learn/
ONE-TIME SETUP
pip install pandas sentence-transformers
FILES (same folder as this script)
old_urls.csv url,title,category,clicks_90d,backlinks (all ~3,800 rows)
new_urls.csv url,title,category (all ~1,400 rows)
tag_map.csv optional: old_url,new_url e.g. /tag/tomatoes/,/learn/vegetables/
category_map.csv optional: old_category,new_hub e.g. Veg Patch,/learn/vegetables/
RUN
python map_redirects.py map --limit 50 # test: your 50 most valuable URLs -> mapping.csv
python map_redirects.py map # full set; saves every 500 rows; re-run to resume
python map_redirects.py export # reads mapping_reviewed.csv -> Cloudflare files
"""
import os
import re
import sys
import numpy as np
import pandas as pd
OLD_HOST = "blog.example.org"
NEW_ORIGIN = "https://www.example.org"
# ---- Settings. Every number is a starting GUESS - tune them on the 50-row test. ----
GOOD_SCORE = 0.80 # confidence below this -> needs review
MIN_SCORE = 0.65 # meaning score below this -> not a match at all
MIN_GAP = 0.05 # best and 2nd-best closer than this -> ambiguous
REVIEW_CLICKS = 500 # clicks_90d at/above this -> always human review
REVIEW_LINKS = 5 # backlinks at/above this -> always human review
REVIEW_410_CLICKS = 50 # unmatched post with this many clicks -> review before 410
MAX_FAN_IN = 15 # warn when more old URLs than this point at one new URL
BATCH = 500 # rows saved per batch
MODEL = "all-MiniLM-L6-v2" # free embedding model; runs on a normal laptop
STOP = {"a", "an", "the", "to", "how", "of", "for", "and", "in", "on", "with", "my",
"your", "is", "are", "why", "what", "when", "do", "best", "guide", "guides",
"beginner", "beginners", "tips", "ultimate", "complete", "easy", "simple"}
POST_RE = re.compile(r"^/\d{4}/\d{2}/[^/]+/$")
COLUMNS = ["old_url", "new_url", "match_type", "confidence", "clicks", "backlinks",
"needs_review", "reason", "second_best", "action", "decision"]
# ---------- Helpers: normalising URLs and words ----------
def read_csv(name):
# utf-8-sig handles CSVs saved by Excel
return pd.read_csv(name, dtype=str, encoding="utf-8-sig").fillna("")
def norm_path(url):
"""'https://blog.example.org/2021/03/Post?utm=x#top' -> '/2021/03/post/'"""
u = str(url).strip()
u = re.sub(r"^https?://[^/]+", "", u, flags=re.I) # drop scheme and host
u = u.split("#")[0].split("?")[0] # drop fragment and query string
u = re.sub(r"/{2,}", "/", u).lower() # your slugs are lowercase
if not u.startswith("/"):
u = "/" + u
if not u.endswith("/"):
u += "/" # one trailing-slash style
return u
def stem(w):
"""Light plural fix so 'tomatoes' = 'tomato' and 'varieties' = 'variety'."""
if w.endswith("oes"):
return w[:-2]
if w.endswith("ies") and len(w) > 4:
return w[:-3] + "y"
if w.endswith("s") and not w.endswith("ss") and len(w) > 3:
return w[:-1]
return w
def content_words(text):
raw = re.findall(r"[a-z0-9]+", str(text).lower())
return {stem(w) for w in raw if len(w) > 1 and w not in STOP and not w.isdigit()}
def clean_title(text):
return " ".join(re.findall(r"[a-z0-9]+", str(text).lower()))
def slugify(text):
return re.sub(r"[^a-z0-9]+", "-", str(text).lower()).strip("-")
def slug_of(path):
parts = [p for p in path.split("/") if p]
return parts[-1] if parts else ""
def url_type(path, category):
if path == "/":
return "home"
if re.match(r"^/page/\d+/$", path):
return "home-pagination"
for prefix in ("tag", "author", "category"):
if path.startswith(f"/{prefix}/"):
return prefix
if re.match(r"^/\d{4}/(\d{2}/)?$", path):
return "date-archive"
if POST_RE.match(path):
if "gift-guide" in path or category.strip().lower() == "gifts":
return "gift-guide" # old gift guides are not kept -> 410
return "post"
return "other"
# ---------- Loading the CSVs ----------
def load_old():
df = read_csv("old_urls.csv")
for col in ("title", "category", "clicks_90d", "backlinks"):
if col not in df:
df[col] = ""
df["path"] = df["url"].map(norm_path)
for col in ("clicks_90d", "backlinks"):
df[col] = pd.to_numeric(df[col], errors="coerce").fillna(0).astype(int)
# '/x', '/x/' and '/x/?utm=1' become one row; their numbers are added up
df = df.groupby("path", as_index=False).agg(
title=("title", "max"), category=("category", "max"),
clicks_90d=("clicks_90d", "sum"), backlinks=("backlinks", "sum"))
df["priority"] = df["clicks_90d"] + 100 * df["backlinks"] # GUESS: 1 backlink ~ 100 clicks
return df.sort_values("priority", ascending=False).reset_index(drop=True)
def load_new():
df = read_csv("new_urls.csv")
df["path"] = df["url"].map(norm_path)
df = df.drop_duplicates("path").reset_index(drop=True)
segs = df["path"].str.strip("/").str.split("/")
df["is_hub"] = segs.map(len) <= 2 # /learn/ and /learn/vegetables/
df["cat"] = segs.map(lambda s: s[1] if len(s) > 1 else "")
df["words"] = [content_words(slug_of(p)) for p in df["path"]]
df["ctitle"] = df["title"].map(clean_title)
return df
def load_pairs(name, key, value):
if not os.path.exists(name):
return {}
d = read_csv(name)
return {k.strip(): v.strip() for k, v in zip(d[key], d[value]) if k.strip()}
def build_ctx(new):
hubs = {c: p for c, p, h in zip(new["cat"], new["path"], new["is_hub"]) if h and c}
cmap = {slugify(k): norm_path(v).strip("/").split("/")[-1]
for k, v in load_pairs("category_map.csv", "old_category", "new_hub").items()}
tag_map = {norm_path(k): v for k, v in load_pairs("tag_map.csv", "old_url", "new_url").items()}
live = set(new["path"]) | {"/learn/"} # /learn/ is your new blog home
return dict(hubs=hubs, cats=set(new["cat"]) - {""}, cmap=cmap, tag_map=tag_map, live=live)
def new_cat(old_slug, ctx):
"""Old category (or tag) slug -> new category slug, or '' if there is none."""
s = ctx["cmap"].get(old_slug, old_slug)
return s if s in ctx["cats"] else ""
def check_target(old_url, new_url, ctx):
"""Safety rules. Returns '' if the redirect is safe, otherwise the problem."""
if not new_url.startswith(NEW_ORIGIN + "/"):
return "target is not on www.example.org"
path = norm_path(new_url)
if path == "/":
return "homepage target (Google treats these like soft 404s)"
if new_url.rstrip("/").lower() == old_url.rstrip("/").lower():
return "self-redirect"
if path not in ctx["live"]:
return "target is not in the new URL list (removed page or typo)"
return ""
# ---------- Embeddings (match by meaning), cached so re-runs are fast ----------
_model = None
def embed(texts, name):
global _model
vec_file, txt_file = f"cache_{name}.npy", f"cache_{name}.txt"
joined = "\n".join(texts)
if os.path.exists(vec_file) and os.path.exists(txt_file):
with open(txt_file, encoding="utf-8") as f:
if f.read() == joined:
return np.load(vec_file)
if _model is None:
from sentence_transformers import SentenceTransformer
_model = SentenceTransformer(MODEL) # downloads ~90 MB the first time
vecs = _model.encode(texts, batch_size=64, normalize_embeddings=True,
show_progress_bar=True)
np.save(vec_file, vecs)
with open(txt_file, "w", encoding="utf-8") as f:
f.write(joined)
return vecs
# ---------- Deciding one old URL ----------
def map_one(r, new, v_old, vec_new, ctx):
path, cat_name = r["path"], r["category"]
kind = url_type(path, cat_name)
segs = [s for s in path.split("/") if s]
row = dict.fromkeys(COLUMNS, "")
row.update(old_url=f"https://{OLD_HOST}{path}", clicks=r["clicks_90d"],
backlinks=r["backlinks"], action="410")
review = []
def go(new_path, how, conf):
row.update(new_url=NEW_ORIGIN + new_path, match_type=how,
confidence=round(float(conf), 2), action="301")
def P(i):
return new.at[i, "path"]
if kind in ("home", "home-pagination"):
go("/learn/", "rule: blog home", 1.0)
elif kind in ("category", "tag"):
base = "/" + "/".join(segs[:2]) + "/"
cat = new_cat(segs[1] if len(segs) > 1 else "", ctx)
if kind == "tag" and base in ctx["tag_map"]:
go(norm_path(ctx["tag_map"][base]), "manual: tag map", 0.70)
review.append("tag -> hub: confirm it truly fits")
elif cat in ctx["hubs"]:
go(ctx["hubs"][cat], f"rule: {kind} -> hub", 0.95 if kind == "category" else 0.75)
if kind == "tag":
review.append("tag -> hub: confirm it truly fits")
else:
row["match_type"] = f"removed: {kind}"
if kind == "category":
review.append("old category has no new hub")
elif kind in ("author", "date-archive", "gift-guide"):
row["match_type"] = f"removed: {kind}"
else: # a post, or an unusual URL
if kind == "other":
review.append("unusual URL type")
cat = new_cat(slugify(cat_name), ctx)
pages = new[~new["is_hub"]] # posts never auto-map to hub pages
cand = pages[pages["cat"] == cat] if cat else pages
old_words = content_words(slug_of(path))
thin = len(content_words(r["title"])) < 2 and len(old_words) < 2
# Step 1a: identical title
ct = clean_title(r["title"])
exact = pages[pages["ctitle"] == ct] if ct else pages.iloc[0:0]
# Step 1b: slug rule - all key words of the new slug appear in the old slug
rule_hit, rule_conf = None, 0.0
fits = cand[cand["words"].map(lambda w: bool(w) and w <= old_words)]
if len(fits):
longest = fits["words"].map(len).max()
top = fits[fits["words"].map(len) == longest]
rule_hit = top.index[0]
rule_conf = 0.75 + 0.15 * longest / max(len(old_words), 1)
if len(top) > 1:
rule_conf = 0.70
review.append("several new slugs fit the old slug")
# Step 2: meaning match (skipped when there is too little text)
sem_hit, sem_score, second, close, cross = None, 0.0, None, False, False
if len(cand) and not thin:
idx = cand.index.to_numpy()
sims = vec_new[idx] @ v_old
order = np.argsort(-sims)
sem_hit, sem_score = idx[order[0]], float(sims[order[0]])
if len(order) > 1:
second = idx[order[1]]
close = sem_score - float(sims[order[1]]) < MIN_GAP
if cat and sem_score < MIN_SCORE: # nothing good in the category: try all
idx2 = pages.index.to_numpy()
sims2 = vec_new[idx2] @ v_old
j = int(np.argmax(sims2))
if sims2[j] >= MIN_SCORE:
sem_hit, sem_score, close, cross = idx2[j], float(sims2[j]), False, True
sem_ok = sem_hit if sem_score >= MIN_SCORE else None
# Step 3: choose
if len(exact) == 1:
i = exact.index[0]
same = not cat or new.at[i, "cat"] == cat
go(P(i), "exact title", 0.98 if same else 0.90)
if not same:
review.append("category changed")
elif rule_hit is not None and sem_ok in (None, rule_hit):
if sem_ok is None:
go(P(rule_hit), "slug rule", rule_conf)
else:
go(P(rule_hit), "slug rule + meaning agrees",
min(0.97, max(rule_conf, sem_score) + 0.05))
elif rule_hit is not None: # the two signals disagree
pick, other = (rule_hit, sem_ok) if rule_conf >= sem_score else (sem_ok, rule_hit)
go(P(pick), "slug rule vs meaning (disagree)", min(rule_conf, sem_score))
review.append("slug rule and meaning disagree")
second = other
elif sem_ok is not None:
go(P(sem_ok), "meaning (embeddings)", sem_score)
if close:
review.append("top two meaning matches are very close")
elif thin:
row["match_type"] = "too little text"
if cat in ctx["hubs"]:
review.append(f"thin: use hub {ctx['hubs'][cat]} only if it truly fits")
else:
row["match_type"] = "no good match"
second = sem_hit
if cross and sem_hit is not None and row["new_url"] == NEW_ORIGIN + P(sem_hit):
review.append("best match is in a different category")
if len(exact) > 1:
review.append("several new pages share this title")
if second is not None and NEW_ORIGIN + P(second) != row["new_url"]:
row["second_best"] = NEW_ORIGIN + P(second)
if row["action"] == "410" and r["clicks_90d"] >= REVIEW_410_CLICKS:
review.append("has traffic but no match")
# Safety rules and review flags for every URL type
if row["action"] == "301":
problem = check_target(row["old_url"], row["new_url"], ctx)
if problem:
row.update(second_best=row["new_url"], new_url="", action="410",
match_type="blocked: " + problem)
review.append("blocked target")
elif row["confidence"] < GOOD_SCORE:
review.append("low confidence")
if r["clicks_90d"] >= REVIEW_CLICKS or r["backlinks"] >= REVIEW_LINKS:
review.append("high traffic/backlinks: always check")
if row["action"] == "410" and r["backlinks"] > 0:
review.append("has backlinks but will be removed")
row["needs_review"] = "YES" if review else "NO"
row["reason"] = "; ".join(review)
return row
# ---------- Commands ----------
def run_map(limit=None):
old, new = load_old(), load_new()
ctx = build_ctx(new)
old_texts = [t if len(content_words(t)) >= 2 else slug_of(p).replace("-", " ")
for t, p in zip(old["title"], old["path"])]
new_texts = [t or slug_of(p).replace("-", " ") for t, p in zip(new["title"], new["path"])]
vec_old, vec_new = embed(old_texts, "old"), embed(new_texts, "new")
todo = old.head(limit) if limit else old # most valuable URLs first
if os.path.exists("mapping.csv"):
done = set(read_csv("mapping.csv")["old_url"])
todo = todo[~(f"https://{OLD_HOST}" + todo["path"]).isin(done)]
print(f"Resuming: {len(done)} rows already in mapping.csv")
batch = []
for n, (i, r) in enumerate(todo.iterrows(), 1):
batch.append(map_one(r, new, vec_old[i], vec_new, ctx))
if len(batch) == BATCH or n == len(todo): # save progress in batches
pd.DataFrame(batch, columns=COLUMNS).to_csv(
"mapping.csv", mode="a", index=False, header=not os.path.exists("mapping.csv"))
print(f"Saved {n}/{len(todo)}")
batch = []
m = read_csv("mapping.csv")
print("\nMatch types:\n" + m["match_type"].value_counts().to_string())
print(f"\nNeeds review: {(m['needs_review'] == 'YES').sum()} of {len(m)} rows")
fan = m.loc[m["action"] == "301", "new_url"].value_counts()
for url, count in fan[fan > MAX_FAN_IN].items():
print(f"CHECK fan-in: {count} old URLs -> {url}")
def run_export():
if not os.path.exists("mapping_reviewed.csv"):
sys.exit("Review mapping.csv first and save it as mapping_reviewed.csv")
m = read_csv("mapping_reviewed.csv")
ctx = build_ctx(load_new())
redirects, gone, problems, pending = {}, [], [], 0
for r in m.itertuples():
src = norm_path(r.old_url)
d = r.decision.strip()
if r.needs_review == "YES" and not d:
pending += 1 # never ship an unreviewed risky row
continue
if d.upper() in ("", "OK"):
d = r.new_url if r.action == "301" else "410"
if d.upper() == "410":
gone.append(src)
continue
target = d if d.startswith("http") else NEW_ORIGIN + norm_path(d)
problem = check_target(r.old_url, target, ctx)
if problem:
problems.append(f"{r.old_url} -> {target}: {problem}")
continue
redirects[src] = NEW_ORIGIN + norm_path(target)
# Subpath matching only where no other listed URL sits underneath
every = sorted(set(redirects) | set(gone))
has_children = {a for a, b in zip(every, every[1:]) if b.startswith(a)}
lines = []
for src in sorted(redirects):
tgt = redirects[src]
sub = "FALSE" if src == "/" or src in has_children else "TRUE"
lines.append(f"{OLD_HOST}{src},{tgt},301,FALSE,FALSE,{sub},FALSE")
if src != "/": # same URL without the trailing slash
lines.append(f"{OLD_HOST}{src.rstrip('/')},{tgt},301,FALSE,FALSE,FALSE,FALSE")
for name, data in (("cloudflare_bulk_redirects.csv", lines),
("gone_410.txt", sorted(gone)), ("export_problems.txt", problems)):
with open(name, "w", encoding="utf-8") as f:
f.write("\n".join(data) + "\n")
print(f"{len(redirects)} redirects -> {len(lines)} rows in cloudflare_bulk_redirects.csv "
"(check this fits your Cloudflare plan's Bulk Redirects limit)")
print(f"{len(gone)} URLs will return 410 (gone_410.txt)")
print(f"{len(problems)} blocked rows (export_problems.txt) - fix them, then export again")
if pending:
print(f"WARNING: {pending} rows need review and have no decision - NOT exported")
if __name__ == "__main__":
args = sys.argv[1:]
if args and args[0] == "map":
run_map(int(args[args.index("--limit") + 1]) if "--limit" in args else None)
elif args and args[0] == "export":
run_export()
else:
print(__doc__)
4. Mapping table template
This is what mapping.csv looks like, filled in with your 7 sample rows and sorted by priority. Old URLs are on blog.example.org and new URLs are on www.example.org. The confidence numbers are examples; your run will produce its own.
| Old URL | New URL | Match type | Confidence | Clicks | Backlinks | Needs review |
|---|---|---|---|---|---|---|
| /2021/03/how-to-start-a-vegetable-garden/ | /learn/vegetables/start-a-vegetable-garden/ | Exact title | 0.98 | 8,200 | 41 | YES (high traffic) |
| /2022/07/why-are-my-tomato-leaves-turning-yellow/ | /learn/vegetables/yellow-tomato-leaves/ | Slug rule + meaning agrees | 0.91 | 4,700 | 8 | YES (high traffic) |
| /2022/02/composting-101/ | /learn/soil/composting/ | Slug rule (title too short for meaning match) | 0.90 | 2,600 | 19 | YES (high traffic) |
| /2021/05/best-tomato-varieties-for-beginners/ | /learn/vegetables/tomato-varieties/ | Slug rule + meaning agrees | 0.95 | 3,100 | 12 | YES (high traffic) |
| /2020/11/garden-gift-guide-2020/ | none (410) | Removed: gift guide | – | 30 | 2 | YES (has backlinks) |
| /tag/tomatoes/ | /learn/vegetables/ | Manual: tag map | 0.70 | 40 | 0 | YES (tag → hub) |
| /author/sam/ | none (410) | Removed: author | – | 5 | 0 | NO |
Notes on the samples
- All four posts need review only because of their traffic. The matches themselves look right. They're your most valuable URLs, so a 10-second check each is worth it.
- Gift guide: you don't keep gift guides and there's no equal page, so 410 is correct. The review is only to look at its 2 backlinks first.
/tag/tomatoes/→/learn/vegetables/is a reasonable fit because the vegetables hub covers tomato content. With 40 clicks and 0 backlinks, a 410 would also be fine. It's your call. (Guess: you'd rather keep it.)
Confidence scale (0–1): exact title = 0.98. Slug rule = 0.75–0.90, rising to 0.97 when the meaning match agrees. Meaning-only matches use the embedding score as-is. Tag → hub = 0.70–0.75.
Needs review = YES when any of these is true:
- high traffic (500+ clicks or 5+ backlinks, a guess)
- confidence under 0.80
- the top two matches are too close to call
- the slug rule and the meaning match disagree
- the match is in a different category
- a tag or thin URL is pointed at a hub
- the URL will be removed but has backlinks
- the URL is unmatched but has 50+ clicks
Extra columns in the CSV: reason (why it's flagged), second_best (the runner-up URL), action (301 or 410) and decision (yours to fill in).
5. QA checklist and post-launch plan
Before launch
- Export reports 0 blocked rows and 0 pending reviews. That means no self-redirects, no homepage targets, and every target is in your new list.
- Fan-in check: every new URL that receives more than 15 old URLs is a genuine merge, not a dumping ground. Look hardest at hubs like
/learn/vegetables/. The blog home's/page/N/listing pages pointing at/learn/is expected. - All ~1,400 new URLs return 200 directly: no redirect, no
noindex, and a canonical tag that points to the page itself. If you use Screaming Frog's list mode, note that the free version stops at 500 URLs, so run 3 batches. - The
blogDNS record is proxied, the Worker is onblog.example.org/*, and nothing blocks crawling of the old subdomain. - Small-batch test: upload a 20–30 row test list. Include a top post, a merged post, a tag, a category, a 410 URL, and a made-up URL (which should return 404). Check each with curl:
Also test the no-slash version,curl -sI https://blog.example.org/2021/03/how-to-start-a-vegetable-garden/ # expect: HTTP/2 301 and location: https://www.example.org/learn/vegetables/start-a-vegetable-garden/ curl -sI https://www.example.org/learn/vegetables/start-a-vegetable-garden/ # expect: HTTP/2 200?utm_source=test,/amp/, andhttp://instead ofhttps://. If http takes two hops (http → https → new), it's most likely Cloudflare's "Always Use HTTPS" acting first. That's acceptable for old http links only. The https versions must be one hop. - Save a copy of the 90-day clicks per old URL now. That's your baseline.
Launch day: crawl test of the old URL list
Upload the full list, turn on the rule, then run this as qa_check.py in the same folder. It takes roughly 20–30 minutes (a guess).
"""
qa_check.py - run AFTER launch. Crawls the old URL list and checks every redirect.
Setup: pip install requests
Needs: old_urls.csv and cloudflare_bulk_redirects.csv in this folder
Run: python qa_check.py -> qa_results.csv (filter the 'result' column for FAIL)
"""
import csv
import time
import pandas as pd
import requests
from map_redirects import OLD_HOST, norm_path, read_csv
expected = {}
with open("cloudflare_bulk_redirects.csv", encoding="utf-8") as f:
for row in csv.reader(f):
expected["https://" + row[0]] = row[1]
old = read_csv("old_urls.csv")
old["clicks_90d"] = pd.to_numeric(old["clicks_90d"], errors="coerce").fillna(0)
old = old.sort_values("clicks_90d", ascending=False)
urls = list(dict.fromkeys(f"https://{OLD_HOST}{p}" for p in old["url"].map(norm_path)))
for u in urls[:50]: # top 50: also test the variants real visitors send
if u != f"https://{OLD_HOST}/":
urls += [u.rstrip("/"), u + "?utm_source=qa", u + "amp/"]
def expected_for(u):
base = u.split("?")[0]
if base.endswith("/amp/"):
base = base[:-4]
return expected.get(base)
session = requests.Session()
session.headers["User-Agent"] = "Mozilla/5.0 (compatible; redirect-qa)"
target_status = {} # each new URL is fetched only once
def fetch(url):
try:
return session.get(url, allow_redirects=False, timeout=20)
except requests.RequestException as e:
return e
results = []
for n, url in enumerate(urls, 1):
want = expected_for(url)
r = fetch(url)
if isinstance(r, Exception):
results.append([url, want or "410/404", "error", "", "", f"FAIL: {r}"])
continue
loc = r.headers.get("Location", "")
hop2 = ""
if loc:
if loc not in target_status:
t = fetch(loc)
target_status[loc] = "error" if isinstance(t, Exception) else t.status_code
hop2 = target_status[loc]
if want:
if r.status_code != 301:
verdict = f"FAIL: first hop is {r.status_code}, not 301"
elif loc != want:
verdict = "FAIL: redirects somewhere other than planned (or loops)"
elif hop2 != 200:
verdict = f"FAIL: target answers {hop2} (chain, loop or broken page)"
else:
verdict = "PASS"
else:
verdict = "PASS" if r.status_code in (404, 410) else f"FAIL: expected 410/404, got {r.status_code}"
results.append([url, want or "410/404", r.status_code, loc, hop2, verdict])
if n % 250 == 0:
print(f"{n}/{len(urls)} checked")
time.sleep(0.1) # be gentle; slow down if Cloudflare starts showing challenges
df = pd.DataFrame(results, columns=["old_url", "expected", "status", "location",
"target_status", "result"])
df.to_csv("qa_results.csv", index=False)
print(df["result"].str.split(":").str[0].value_counts().to_string())
Pass rules
- Every mapped URL makes one 301 hop to the exact planned URL, and that URL returns 200.
- Removed URLs return 410. Unknown URLs return 404.
- Any 302/307, any 200 on
blog.example.org, or any 3xx at the target is a FAIL. A 3xx at the target covers both chains and loops. - Fix the failures and re-run until you get 0 FAIL. If you see 403/503 responses, Cloudflare is challenging the script. Slow it down or allow your IP.
- Relevance: open 30 random PASS rows side by side (old title against the new page). A redirect can be technically perfect and still be wrong for the reader.
Week 1
- Internal links: search the new site's content, menus, footer, related-post widgets and email templates for
blog.example.org. Replace every hit with its final URL.cloudflare_bulk_redirects.csvis your find-and-replace list: column 1 is the old URL (addhttps://in front) and column 2 is the new URL. - Sitemaps: the
www.example.orgsitemap should list only the live/learn/URLs (200 pages only, with no redirected or 410 URLs). Submit it in Search Console and remove the old blog sitemap. - Search Console: keep the
blog.example.orgproperty verified. Use URL Inspection on your top 20 old URLs to confirm Google sees the 301. - Backlink outreach: ask the linking sites to update their links to your top pages. Start with the vegetable garden guide (41 backlinks), Composting 101 (19) and Tomato Varieties (12). Redirects pass signals, but direct links are safer for the long term.
Every week for the first 3 months, then monthly
- 404 check:
- In Cloudflare's HTTP traffic analytics, filter to host
blog.example.organd status 404. Thanks to the Worker, these are only URLs nobody mapped; the 410s are your deliberate removals. - Also check Search Console's Pages report for "Not found (404)" and "Soft 404", on both properties.
- For each 404 with real hits or backlinks: add a row to the Bulk Redirect list if a truly relevant page exists. Otherwise leave it.
- In Cloudflare's HTTP traffic analytics, filter to host
- 404s on
www.example.org/learn/usually mean broken internal links. Fix them at the source. - Traffic: compare
/learn/clicks against your saved 90-day baseline. Expect some ups and downs for several weeks (a guess; it varies by site). - Re-run
qa_check.pymonthly, and again whenever a/learn/page is merged or moved. When that happens, update its old blog rows to the newest URL straight away, or you'll create a chain.
Keep the redirects
- Keep the Bulk Redirect list, the rule, the Worker and the
blogDNS record for at least 1 year, and ideally permanently. They cost nothing to keep, and pages with backlinks keep sending visitors for years. - Set a reminder for month 12. The goal then is to confirm everything still passes, not to delete anything.
Lines like “check: pass” or “fixed” are the model talking to itself. The prompt tells it to review its own work before answering; that review is part of the output.
The prompt
First lines open so you can see how it is built. The rest opens after purchase.
#ROLE You are a migration SEO specialist who builds large redirect maps. Help me create an accurate 301 redirect map for my site move or content clean-up. #INPUTS Fill in every line. Leave a line blank if you don't know it. - Old site and new site: [OLD URL -> NEW URL] - Number of old URLs to map: [NUMBER] - Old URL list (CSV with URL, title, category, clicks, backlinks if available): [PASTE OR ATTACH]
How to use it
- Buy, then open it in your account.
- Copy the prompt into ChatGPT, Claude or Gemini.
- Replace the 7 inputs with your product.
- Run it. Use the output. Re-run with a different tone if you like.
Pro tips
- Include clicks and backlinks in the old URL list. They decide which matches a human must check first.
- Run a small test batch before the full set. Bad matches are much cheaper to catch early.
- Keep redirects for at least a year, and update internal links to the new URLs right away.
Before you buy
- Will it work for my product?
- Yes, if you can fill the 7 inputs. If the output is bad with your inputs, email us: we fix the prompt and refund you.
- Do I download a file?
- No. It lives in your account with a copy button, and updates when we improve it.
- Which model is best?
- Best on Claude. Works in ChatGPT, Claude and Gemini.
Works well with this
Prompts people use in the same campaign.
More in Migrations & Launches
Buying more than two? Lifetime is cheaper.
Every prompt, every category, forever. $59 once. Nothing to download, nothing to renew.
This prompt
$3$7
- ✓ Instant access in your account, with a copy button
- ✓ Example input and real output included
- ✓ 7-day money-back, no form
Or get every prompt, forever
Lifetime Access · $59 $149 — all categories, all future prompts, rewrites included.
Get lifetime accessCard or PayPal · taxes at checkout · nothing to download
Not the one you need?
Browse every prompt by category and sub-category.