Sub topic 11
Writing a small link and redirect checker
This chapter assumes you can run curl from a command line and read basic Python. You should also know what 301, 302, 404, and 410 mean. The previous chapters covered tracing a single URL with curl. Here you automate that trace for a list of URLs.
What the checker must do
A useful checker answers three questions for each URL:
- What is the final status code?
- How many hops did it take to get there?
- Did the path end normally, loop, or run past a hop limit?
Letting the HTTP library follow redirects hides the hops. The checker therefore turns automatic redirects off and follows each Location header itself.
The script
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
Each pass through the while loop makes one request and records the status and URL. stream=True followed by resp.close() avoids downloading the body, because only the headers matter.
urljoin resolves relative Location values. A header such as Location: /new-page becomes a full URL based on the current one.
The seen set detects loops. If a redirect points at a URL already visited, the function records that URL with a None status and returns "loop". The max_hops limit catches very long chains that are not strict loops, such as a URL that adds a new query string on every hop.
Reading the results
| Outcome | Hops | What to do |
|---|---|---|
| `ok`, status 200 | 1 | Nothing. |
| `ok`, status 301 then 200 | 2 | Update links to point at the final URL. |
| `ok`, three or more hops | 3+ | Collapse the chain into one redirect. |
| `ok`, status 404 or 410 | any | Fix the source link or add a redirect. |
| `loop` | any | Correct the server rules that cause it. |
Limits of this version
The script handles one URL at a time and sends no custom User-Agent. It also does not retry after timeouts. A requests exception, such as a DNS failure, will stop it. Wrap the call in try/except requests.RequestException before running it over a long list. Some servers answer HEAD differently from GET, which is why this version uses GET. Keep your request rate low so the check does not look like an attack on your own server.
Exercise
A URL redirects with a 301 to /a, /a redirects with a 302 to /b, and /b returns 200. What does trace return, and what should you change on the site?
Show answer
It returns three hops, (301, original), (302, /a), and (200, /b), with outcome "ok". This is a chain of two redirects. Change the original URL's redirect so it goes straight to /b, and update internal links to use /b directly.