Sub topic 16
Planning Redirects for Migrations and URL Changes
This chapter assumes you can read HTTP status codes, tell 301 from 302/307/308, and run curl. It also assumes you have edited an nginx or Apache config. Earlier chapters covered chains, loops, and soft 404s. Here you apply them to the situation that creates the most broken URLs at once: a migration.
Why migrations need a plan
A redesign, a CMS change, a move to HTTPS, a domain change, or a new URL structure can break thousands of URLs in one deploy. Each old URL that stops working loses its inbound links, its bookmarks, and the search history attached to it.
Redirects added after launch, in a hurry, tend to produce the problems you already know:
- Chains, such as
/ato/bto/c. - Loops.
- Blanket redirects to the homepage.
- Forgotten URLs that return 404.
A redirect map is a plan you write and test before launch. It lists every old URL and where it should go.
Step 1: Inventory the old URLs
Collect old URLs from several sources, because no single source is complete:
- The sitemap. It lists the pages you want indexed, but not everything that exists.
- A crawl. It finds linked pages and internal links to old paths.
- Server logs. They show what users and bots actually request, including old URLs nobody links to anymore.
- Search Console. It shows pages that get impressions and clicks.
- Backlink exports. They show URLs that other sites link to.
Merge the lists and remove duplicates. Then rank the URLs using the criteria from the prioritization chapter: traffic, inbound links, and whether the URL is internal or external. High-value URLs get hand-checked mappings. Low-value URLs can use pattern rules.
Do this before the migration, while the old site is still live. Afterward you can only reconstruct the list from logs.
Step 2: Decide what happens to each URL
Every old URL needs exactly one outcome.
| Situation | Action | Status |
|---|---|---|
| Page moved, same content | Redirect to the new equivalent | 301 (or 308 to preserve the method) |
| Several pages merged into one | Redirect each old URL to the merged page | 301 |
| Page removed, close replacement exists | Redirect to the replacement | 301 |
| Page removed, no real replacement | Return a gone response | 410 (or 404) |
| Temporary move, such as maintenance | Redirect temporarily | 302 or 307 |
The key rule is that the destination must be equivalent to the source. A redirect to a page about something else is treated by search engines much like a soft 404. If no equivalent exists, a 410 is more honest and more useful.
Step 3: Write the map
A redirect map is a two-column file: old path, new path. A spreadsheet works well for review, and CSV exports easily to server config.
old,new
/blog/2019/05/redirects,/guides/redirects
/products/widget-a,/shop/widgets/a
/about-us.html,/about
/old-pricing,/pricingFollow these rules:
- Point at the final URL. If
/old-pricinggoes to/pricing, and/pricingitself redirects to/plans, write/old-pricing,/plans. Collapse chains at planning time. - Use patterns for structural changes. If
/blog/2019/05/slugbecomes/guides/slugfor hundreds of posts, one regex rule is easier to maintain than hundreds of rows. Test the regex on real URLs from your inventory. - Decide about query strings and trailing slashes. Decide whether
/pageand/page/are the same, and whether query parameters carry over. Write the decision down and apply it consistently. - Include protocol and host changes. For an HTTPS or domain move, every old host and path combination needs a single-hop redirect to the final canonical form.
Step 4: Validate the map before it ships
You can check the map as data, with no server needed. The script below reads the map and reports duplicate sources, self-redirects, targets that are not paths, and chains. It also finds loops and suggests the final destination for each chain.
import csv
import io
SAMPLE = """old,new
/old-pricing,/pricing
/pricing,/plans
/team,/about
/about,/team
/docs/start,/docs/start
/docs/start,/docs/intro
/faq,faq.html
"""
def check(rows):
mapping = {}
problems = []
for line_no, row in enumerate(rows, start=2):
old, new = row["old"].strip(), row["new"].strip()
if not new.startswith("/"):
problems.append(f"line {line_no}: target {new!r} is not a path")
if old == new:
problems.append(f"line {line_no}: {old} redirects to itself")
if old in mapping:
problems.append(f"line {line_no}: duplicate source {old}")
mapping[old] = new
for old in mapping:
seen = [old]
current = mapping[old]
while current in mapping and current not in seen:
seen.append(current)
current = mapping[current]
if current in seen and len(seen) > 1:
problems.append(f"loop: {' -> '.join(seen + [current])}")
elif len(seen) > 1:
problems.append(f"chain: {old} should point to {current}")
return problems
if __name__ == "__main__":
reader = csv.DictReader(io.StringIO(SAMPLE))
for problem in check(list(reader)):
print(problem)Replace io.StringIO(SAMPLE) with open("redirect-map.csv", newline="") to check your own file. Run this in your build pipeline so a bad map cannot be deployed.
Step 5: Put the map into server config
For a large map, avoid hundreds of separate location blocks. In nginx, use a map that includes the file. This one must live in the http context.
map $uri $redirect_target {
default "";
include /etc/nginx/redirect-map.conf;
}
server {
listen 80;
server_name example.com;
if ($redirect_target) {
return 301 $redirect_target$is_args$args;
}
}The included file holds one rule per line, each ending in a semicolon:
/old-pricing /plans;
/about-us.html /about;
/products/widget-a /shop/widgets/a;$uri does not contain the query string, so the $is_args$args suffix carries it over. Drop that suffix if the new site should discard old parameters. For patterns, use a regex key such as ~^/blog/\d{4}/\d{2}/(.+)$ /guides/$1;. Regex keys are checked in file order, after exact matches. After editing, run nginx -t before reloading.
In Apache, use Redirect for single paths and RedirectMatch for patterns:
# Requires mod_alias
Redirect 301 /old-pricing /plans
RedirectMatch 301 ^/blog/[0-9]{4}/[0-9]{2}/(.+)$ /guides/$1
Redirect gone /discontinued-productRedirect gone returns 410. Apache applies Redirect rules in the order the modules process them, so keep patterns and exact paths from overlapping.
Step 6: Test, launch, and watch
Test the live redirects with the tools from earlier chapters, using the inventory as input. For each old URL, check three things: the status is a single 301 (not a chain), the destination matches the map, and the final status is 200.
while read -r path; do
curl -sL -o /dev/null -w "$path %{num_redirects} hop(s) -> %{http_code} %{url_effective}\n" "https://example.com$path"
done < old-urls.txtAny line that shows more than 1 hop, or a final code other than 200, needs a fix. Intentional 410 URLs are the exception, and they should show no redirect.
After launch:
- Watch the 404 report in the logs for a few weeks. The
awkcommand from the log-analysis chapter shows which old URLs you missed. Add them to the map and redeploy. - Check Search Console for new "Not found" or "Page with redirect" reports.
- Update internal links, canonical tags, and the sitemap to the new URLs, so your own pages do not depend on redirects.
- Keep the redirects for at least a year. Keep them longer if external sites still link to the old URLs. Removing them early recreates the broken links you planned around.
Common errors
- Mapping to a URL that redirects again. Run the validator after every map change.
- Forgetting the old host or HTTP variants.
http://www.example.com/xis a different URL fromhttps://example.com/x. - Using 302 for a permanent move. Search engines may keep the old URL indexed.
- Mixing regex and exact rules without testing order. A broad pattern can capture URLs you meant to map individually.
Exercise
Your map contains /a,/b and /b,/c. What goes wrong at runtime, and how should the map be changed?
Show answer
A request for /a receives a 301 to /b, then a second 301 to /c, which is a two-hop chain. Change the first row to /a,/c, and keep /b,/c, so every old URL reaches the final page in one hop. The validator script reports this as a chain and names the target.
Exercise
A product line is discontinued, and nothing on the new site is equivalent to those pages. Which response should the old URLs return, and why not redirect them to the homepage?
Show answer
Return 410 Gone (or 404 if you do not need the stronger signal). A redirect to an unrelated page, such as the homepage, is often treated as a soft 404 and sends visitors somewhere they did not ask for.