Sub topic 5
Redirect chains and loops
This chapter assumes you know what a status code is, the difference between permanent (301, 308) and temporary (302, 307) redirects, and how to read headers with curl. Here you will learn what chains and loops are, why they hurt, how to spot them, and how to remove them.
What a redirect chain is
A redirect chain is a sequence of two or more redirects between the URL a client requested and the URL that finally returns content. Each redirect is a "hop". A single redirect is normal. A chain costs a full round trip per extra hop.
Chains rarely get designed. They build up as rules are added over the years:
- In 2019 the site moves from
http://tohttps://. - In 2021 the
wwwhost is dropped in favor of the bare domain. - In 2023 a blog post is renamed from
/old-pageto/new-page.
Each change adds a rule that points at the URL that was current at the time. A request for http://www.example.com/old-page then passes through every rule in order.
What a redirect loop is
A redirect loop is a path where a URL eventually redirects back to a URL already visited, so the client can never reach a final response. Browsers stop after a limit and show an error such as ERR_TOO_MANY_REDIRECTS. curl stops after 50 redirects by default when you use -L. Googlebot gives up after a small number of hops (Google documents following up to 10) and treats the URL as an error.
Common causes:
- Two rules that undo each other. One forces
www, another strips it. - A CMS and a web server both enforcing a trailing-slash policy, but with opposite choices.
- HTTPS forced at the origin while a CDN or load balancer talks to the origin over HTTP. The origin sees HTTP, redirects to HTTPS, the CDN fetches HTTP again, and so on.
- A redirect from
/ato/badded next to an older redirect from/bto/a. - A redirect to a login page that redirects back when cookies are missing. Crawlers send no cookies, so they loop where you do not.
Why they matter
- Latency. Every hop adds a DNS lookup (if the host changes), a connection, a TLS handshake, and a request. On mobile networks a hop can cost hundreds of milliseconds.
- Crawl budget. A crawler spends one request per hop. On large sites, chains waste requests that could have fetched real pages.
- Signals. Google follows permanent redirects and consolidates signals to the target, but long chains risk being abandoned before the target is reached. Fewer hops is safer.
- Loops are outages. A URL in a loop has no content at all for users or crawlers. Search engines will report it as a redirect error.
Seeing the chain with curl
Use -I for a HEAD request and -L to follow redirects. Filtering to the status and Location lines gives a compact view of every hop:
curl -sIL https://example.com/old-page | grep -iE '^(HTTP|location)'A chain looks like this:
HTTP/2 301
location: https://example.com/old-page
HTTP/2 301
location: https://example.com/new-page
HTTP/2 200For a one-line summary, use write-out variables:
curl -sL -o /dev/null -w '%{num_redirects} redirects, final status %{http_code}, final URL %{url_effective}\n' https://example.com/old-pageAnything with num_redirects above 1 is a chain. A loop makes curl fail with Maximum (50) redirects followed. Add --max-redirs 10 to fail faster.
Tracing hop by hop in a script
curl hides detail when it follows redirects for you. A script that disables automatic redirects can record each hop, resolve relative Location values, and detect a loop directly:
import requests
from urllib.parse import urljoin
REDIRECT_CODES = {301, 302, 303, 307, 308}
def trace(url, max_hops=10):
hops = []
seen = {url}
while len(hops) < max_hops:
resp = requests.get(url, allow_redirects=False, timeout=10, stream=True)
resp.close()
hops.append((resp.status_code, url))
location = resp.headers.get("Location")
if resp.status_code not in REDIRECT_CODES or not location:
return hops, "ok"
url = urljoin(url, location)
if url in seen:
hops.append((None, url))
return hops, "loop"
seen.add(url)
return hops, "too_many_hops"
if __name__ == "__main__":
hops, outcome = trace("https://example.com/old-page")
for status, hop_url in hops:
print(status, hop_url)
print("outcome:", outcome)How it works:
allow_redirects=Falsemakesrequestsreturn the 3xx response itself, so you see every hop.urljoinhandles relativeLocationheaders such as/new-page.- The
seenset detects a loop as soon as a URL repeats. Themax_hopslimit catches very long chains and loops that change the URL each time, for example by appending a query string. stream=Truefollowed byresp.close()avoids downloading bodies you do not need.
Interpret the result like this:
| Outcome | Hops | Meaning | Action |
|---|---|---|---|
| `ok`, final 200 | 1 | Healthy page, no redirect | None |
| `ok`, final 200 | 2 | Single redirect | Fine, update internal links |
| `ok`, final 200 | 3 or more | Chain | Collapse to one hop |
| `ok`, final 404 or 410 | any | Redirect to a dead page | Fix the target or the source link |
| `loop` | any | URL repeats | Fix the conflicting rules |
| `too_many_hops` | 10 | Long chain or unstable loop | Inspect the rules by hand |
Finding chains at scale
Tracing one URL by hand does not scale. Use these sources:
- Crawler reports. Most site crawlers have a redirect chains report and a loops report. Crawl with "follow redirects" enabled so the crawler records every hop.
- Server logs. Count 301 and 302 responses by URL. A URL that is requested often and always returns a redirect is a good candidate for a link fix.
- Search Console. The page indexing report lists "Page with redirect" and "Redirect error" entries. Redirect error covers loops and chains that are too long.
- Your own checker. Run the
tracefunction over a list of URLs from your sitemap and internal links.
Fixing chains and loops
Collapse chains to one hop
The goal is that every old URL redirects once, directly to the final URL. Do not edit the last hop only. Rewrite every rule in the chain so it points at the final destination.
- Trace the old URL and note the final URL.
- Find every rule that matches a URL in the chain, including rules for earlier versions of the URL.
- Change each rule's target to the final URL.
- Re-trace and confirm one hop.
In nginx, the direct rule is:
# Redirect an old URL straight to its final destination (one hop)
location = /old-page {
return 301 /new-page;
}In Apache with mod_alias, use the full final URL:
# Requires mod_alias
Redirect 301 /old-page https://example.com/new-pageProtocol and host normalization still adds a hop for requests on the wrong scheme or host. That is acceptable, but keep it to a single combined rule that sends http://www.example.com/anything to https://example.com/anything in one step, not two.
Update the links, not only the redirects
A redirect is a safety net. If your own pages link to /old-page, every visitor and crawler pays for a hop. Update internal links, canonical tags, and sitemap entries to the final URL. Sitemaps should list only URLs that return 200.
Break loops
- Trace the looping URL and list the sequence of URLs. The repeat shows which two rules conflict.
- Decide which URL is canonical (for example, https, no
www, no trailing slash). - Keep one rule per direction and remove the opposite one.
- If a CDN is involved, check which scheme it uses to reach the origin. Make the origin trust the
X-Forwarded-Protoheader rather than assuming HTTP. - Test with cookies disabled, because crawlers send none.
Edge cases
- Redirects to a dead end. A chain whose last hop is a 404 is worse than a plain 404, because it adds hops and still fails. Fix the target.
- Mixed permanent and temporary hops. If one hop in a chain is a 302, search engines may treat the path as less certain. Use 301 or 308 for permanent moves throughout.
- Method changes. A 301 or 302 can cause clients to change POST into GET. If a form posts to a URL that is redirected, use 307 or 308 to preserve the method.
- Query strings.
return 301 /new-page;in nginx drops the query string. Usereturn 301 /new-page$is_args$args;to keep it. - Fragments. The
#fragmentpart is never sent to the server, so a redirect cannot see it. Browsers carry it over to the target unless the target specifies its own.
Exercise
A trace of http://www.example.com/a shows 301 to https://www.example.com/a, then 301 to https://example.com/a, then 301 to https://example.com/b, then 200. What is the problem, and what should you change?
Show answer
The URL passes through three redirects, so it is a chain. Change the rules so that http://www.example.com/a redirects once, with a 301, directly to https://example.com/b. Also rewrite the intermediate rules (/a to /b on the final host) to point at /b, update internal links and the sitemap to use https://example.com/b, and re-trace to confirm one hop.
Exercise
Your trace function returns loop for https://example.com/docs. The sequence is /docs to /docs/ to /docs. What most likely causes this, and how do you fix it?
Show answer
One rule adds a trailing slash and another removes it. This often happens when the web server and the CMS enforce opposite trailing-slash policies. Pick one form as canonical, remove the opposing rule, then re-trace with curl to confirm a single 200 response.