Dev.to WebDev 🛠 Dev 👁 0 📖 5 min read

How to find redirect chains and redirect loops with a short Python script (and why a 200 at the end can still be a problem)

Scheduled broken-link and redirect checks that tell you the moment a link breaks — linkbruno.com Most link checkers report the final status of a URL. If that status is 200, the link is marked good. That hides a lot of

Scheduled broken-link and redirect checks that tell you the moment a link breaks — linkbruno.com

Most link checkers report the final status of a URL. If that status is 200, the link is marked good. That hides a lot of rot: a URL that hops three or four times before it lands, a www-to-apex-to-https-to-trailing-slash dance that used to be one hop, or a loop that only shows up as a timeout.

A chain is not a 404, but it is still a problem. It is slower, it drops methods and sometimes query strings, it splits link equity, and it breaks the day one of the middle hops disappears. Here is a short script that makes the hops visible.

What to collect

For each URL you care about — pages on your site, and the outbound links on those pages — you want:

  • every hop's URL, status, and Location
  • the final URL and status
  • whether a hop went back to a URL already seen (a loop)
  • whether the chain is longer than you want (I flag more than one hop; two if you deliberately send HTTP and www to a single canonical)

requests follows redirects by default and throws the history away if you only look at the last response. Use allow_redirects=False and walk the chain yourself, or inspect response.history plus the final response. Walking it yourself gives you control over loops and hop limits.

import sys
import requests

MAX_HOPS = 8
TIMEOUT = 15
HEADERS = {"User-Agent": "redirect-chain-check/1.0"}

def chain(url):
    seen = []
    current = url
    for _ in range(MAX_HOPS):
        if current in {u for u, _ in seen}:
            seen.append((current, "LOOP"))
            return seen
        try:
            r = requests.get(
                current,
                allow_redirects=False,
                timeout=TIMEOUT,
                headers=HEADERS,
            )
        except requests.RequestException as e:
            seen.append((current, f"ERROR:{type(e).__name__}"))
            return seen
        seen.append((current, r.status_code))
        if r.status_code not in (301, 302, 303, 307, 308):
            return seen
        location = r.headers.get("Location")
        if not location:
            seen.append((current, "REDIRECT_WITHOUT_LOCATION"))
            return seen
        current = requests.compat.urljoin(current, location)
    seen.append((current, "TOO_MANY_HOPS"))
    return seen

if __name__ == "__main__":
    for raw in sys.stdin:
        url = raw.strip()
        if not url or url.startswith("#"):
            continue
        hops = chain(url)
        statuses = [str(s) for _, s in hops]
        final_ok = statuses[-1] == "200" and len(hops) == 1
        flag = "OK" if final_ok else "CHAIN"
        if any(s == "LOOP" or s == "TOO_MANY_HOPS" for s in statuses):
            flag = "LOOP"
        print(f"{flag}\t{url}\t{' -> '.join(f'{u} ({s})' for u, s in hops)}")

Feed it a list of URLs, one per line. A crawl of your own pages, a sitemap, or the output of an existing link extractor all work.

How to read the output

OK — the URL returned a non-redirect on the first hop. Fine.

CHAIN — it got somewhere, but not in one hop. Look at the middle URLs. Common patterns:

  • http://example.com/x → https://example.com/x → https://www.example.com/x → https://www.example.com/x/ (four hops that should be one 301 to the canonical form)
  • an old path that 302s to a marketing tool that 301s back to a new path
  • a trailing-slash hop that should have been handled in the first redirect

LOOP — two URLs point at each other (often slash vs no-slash, or www vs apex, each assuming the other is canonical), or a hop limit was hit. Loops are outages for anyone who follows the link. Fix them before you do anything about long chains.

ERROR — timeouts, DNS, TLS. Those are broken links, not chain problems, but you want them in the same report.

Why a final 200 is not enough

Redirects are not all equal. A 301 may be cached by browsers and CDNs for a long time; a mistaken 301 is expensive to undo. A 302 or 307 may drop or change a POST, and some clients will drop query strings on a hop even when the spec says they shouldn't. I have seen login and payment return URLs "work" in a checker (final 200) and fail for users because a mid-chain hop stripped ?token= or ?session=.

When you flag a chain, open the hops and ask:

  1. Can this be one redirect from the old URL to the final URL?
  2. Does every hop keep the query string and the hash? (The hash never leaves the browser; mid-chain problems are about query strings and methods.)
  3. Is any hop a 302 that should be a 301, or a 301 you are not sure about?
  4. Does any hop leave your domain and come back? Those break more often than internal hops.

A checker that only records the final 200 will give a chain or a loop a passing grade until a middle hop disappears. linkbruno.com checks your URLs and their redirects on a schedule, so a new hop, a loop, or a redirect that starts failing shows up in a report the same day.

Where to run it

Run it in CI against the preview deploy for internal URLs, and on a schedule against production for everything, including outbound links. Preview is where you catch a new slash rule or locale prefix that just created a thousand two-hop chains. Production is where you catch the partner URL that started bouncing through a tracking domain.

Don't follow redirects into the open web without a hop limit and a time budget. A single open redirect, or a URL that 302s to a huge file, will ruin a naive crawler. The script above stops at eight hops and fifteen seconds, which is enough to flag a loop and cheap enough to run often.

Related reading

What's the longest redirect chain you've found on a site that was "fine" according to the checker? How many hops was it, and what started it?

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.