Sub topic 11
Writing a small link and redirect checker
This chapter builds a Python script that reads a list of URLs, follows each redirect chain one hop at a time, and reports errors, chains, and loops. It automates the manual curl tracing from the previous chapters.
You are assumed to know the following:
- Status codes and redirect types (301, 302, 307, 308).
- What a redirect chain and a loop are.
- Basic Python, and how to install a package with
pip.
Install the one dependency with pip install requests.
What the checker must decide
A checker answers one question per URL: what happens between the first request and the last response? Each URL falls into one of the outcomes below.
| Outcome | Meaning | Typical action |
|---|---|---|
| ok | Final status 2xx with no redirects | None |
| redirect | One redirect, then a 2xx | Update the link to the final URL if you control it |
| chain | Two or more redirects before the final response | Collapse to one hop |
| loop | A URL appears twice in the path | Fix the server rule |
| too_many_hops | More redirects than the limit allows | Treat like a loop and investigate |
| broken | Final status 4xx | Fix the link, redirect, or return 410 |
| server_error | Final status 5xx | Check the server and retest later |
| error | Timeout, DNS failure, or TLS failure | Retest, then investigate |
The script cannot detect soft 404s. A page that says "not found" but returns 200 looks healthy to a status-code check. Detecting those needs content checks, which are outside this chapter.
The tracing loop
The checker must not let the HTTP library follow redirects automatically. If it does, you only see the final response, and a loop surfaces as a generic exception. Setting allow_redirects=False gives you control of each hop.
Three details in the loop matter:
urljoinresolves relativeLocationvalues such as/new-pageagainst the current URL. Redirects with relative targets are legal and common.- The
seenset detects loops. Without it, a loop would run until the hop limit, and you could not tell a loop from a long chain. stream=Truefollowed byclose()avoids downloading the response body. You only need the status line and headers.
The complete script
Save this as check_links.py. It reads one URL per line from a file, checks them in parallel with a small thread pool, and exits with status 1 if any URL has a problem. That exit code lets you run it in a CI job.
import sys
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urljoin
import requests
REDIRECT_CODES = {301, 302, 303, 307, 308}
USER_AGENT = "link-checker/1.0 (+https://example.com/contact)"
def trace(url, session, max_hops=10):
hops = []
seen = {url}
while len(hops) < max_hops:
try:
resp = session.get(url, allow_redirects=False, timeout=10, stream=True)
except requests.RequestException as exc:
hops.append((type(exc).__name__, url))
return hops, "error"
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"
def classify(hops, outcome):
if outcome != "ok":
return outcome
final = hops[-1][0]
redirects = len(hops) - 1
if final >= 500:
return "server_error"
if final >= 400:
return "broken"
if 300 <= final < 400:
return "broken" # redirect status with no usable Location
if redirects >= 2:
return "chain"
if redirects == 1:
return "redirect"
return "ok"
def check(url):
with requests.Session() as session:
session.headers["User-Agent"] = USER_AGENT
hops, outcome = trace(url, session)
return url, hops, classify(hops, outcome)
def main(path):
with open(path, encoding="utf-8") as f:
urls = [line.strip() for line in f if line.strip()]
problems = 0
with ThreadPoolExecutor(max_workers=4) as pool:
for url, hops, label in pool.map(check, urls):
path_text = " -> ".join(f"{status} {u}" for status, u in hops)
print(f"{label.upper():14} {path_text}")
if label != "ok":
problems += 1
print(f"\n{len(urls)} URLs checked, {problems} need attention")
return 1 if problems else 0
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("usage: python check_links.py urls.txt")
sys.exit(main(sys.argv[1]))Create urls.txt with a few addresses, then run the script:
printf '%s\n' https://example.com/ https://example.com/old-page > urls.txt
python check_links.py urls.txtEach output line starts with the label, followed by the full path. A chain looks like CHAIN 301 http://example.com/a -> 301 https://example.com/a -> 200 https://example.com/a/. A loop ends with None as the status of the repeated URL.
Design decisions and gotchas
GET instead of HEAD
A HEAD request is cheaper, but some servers answer it incorrectly. They return 405 or 404 for HEAD while GET works. Using GET with stream=True avoids those false positives, and close() stops the body from downloading. If you must use HEAD for volume reasons, retry with GET before you report a 4xx.
Be a polite client
The script identifies itself with a User-Agent that includes a contact URL. Keep max_workers low when checking your own production server, and add a delay for external sites. Many sites answer fast, repeated requests with 429 or 403. Treat those results as "retest later" rather than "broken". Never point the checker at sites you have no reason to test.
Errors are results
Network failures are caught and recorded as error hops, so one bad host does not stop the run. A timeout can be temporary, so a stricter version would retry once before reporting.
Fragments and normalization
A fragment (#section) is never sent to the server. Strip it before checking, and deduplicate the list, or you will test the same page many times. The loop detector compares exact strings, so https://example.com/a and https://example.com/a/ count as different URLs. That is the correct behavior. A real redirect from one to the other is a hop, not a loop.
Limits of status-based checks
The script cannot see these problems:
- Soft 404s (a 200 response with "not found" content).
- Links that exist only after JavaScript runs.
- A redirect that sends everything to the home page. It returns 200 and looks healthy, but it is usually a soft 404 in disguise.
A cheap partial check is to flag any redirect whose final URL is the site's home page.
Extending it
Common next steps, in order of usefulness:
- Add a retry for
errorandserver_errorresults before reporting. - Write results to a CSV file so you can sort by label and compare runs.
- Feed it the 404 URLs from your server log, using the
awkcommand from the log-analysis chapter, to confirm which are still broken. - Run it on a schedule or in CI and fail the job when new problems appear.
Exercise
A URL in your list returns 301 to https://example.com/b, which returns 302 to https://example.com/c, which returns 200. What label does the script give it, and why does the final 200 not make it "ok"?
Show answer
It is labelled "chain". The trace has two redirects (301 and 302) before the 200, so classify finds redirects >= 2 and returns "chain". A 200 final status only means the destination works. The script reports every URL that needs more than one hop, because each extra hop adds latency and risk, and the link should point at https://example.com/c directly.
Exercise
The script reports a loop for https://example.com/a, but curl -sIL seems to stop after 50 redirects with an error. Why does the script report the problem faster, and which line of the code does it?
Show answer
The script remembers every URL it has visited in the seen set. When urljoin(url, location) produces a URL already in seen, the check if url in seen returns the "loop" outcome immediately. The curl -L command has no such memory, so it keeps following until it reaches its own redirect limit.