Sub topic 17
Keeping links healthy over time
This chapter covers how to stop broken links from coming back after you have fixed them. It assumes you can read HTTP status codes, trace a redirect with curl, and edit nginx or Apache configuration. It also assumes you have seen the checker script from the earlier chapter on writing a small link and redirect checker.
A one-time cleanup decays. Editors delete pages, developers rename routes, partner sites reorganize, and old redirects get removed. Keeping links healthy means turning the checks you already know into a routine that runs without you.
Why links break again
Most new breakage comes from a short list of events:
- Content edits. An editor changes a page slug, deletes a page, or pastes a link with a typo.
- Deployments. A release renames a route, changes trailing-slash behavior, or switches a site from HTTP to HTTPS without updating hard-coded links.
- Redirect rule removal. Someone tidies the config and deletes a redirect that external sites and search engines still depend on.
- External link rot. A site you link to moves or disappears. You cannot prevent this, only detect it.
- Migrations. URL structure changes with a redesign, CMS swap, or domain change, and some old URLs are missing from the redirect map.
Each cause has a matching control. Prevent what you can at the source, check at deploy time, and monitor on a schedule for everything else.
Build a layered system
No single check catches everything. Use several layers, each with a different cost and speed.
| Layer | When it runs | What it catches | Cost |
|---|---|---|---|
| Editor-time validation | While content is written | Typos, links to unpublished or deleted pages | Low |
| Pre-deploy checks (CI) | On every pull request or release | Broken internal links, missing redirects, new chains | Low |
| Post-deploy smoke test | Right after release | A key set of URLs returning the wrong status | Low |
| Scheduled crawl | Weekly or nightly | Slow decay, external link rot, soft 404s | Medium |
| Log and Search Console review | Weekly or monthly | Real URLs that users and bots request and fail on | Low |
Check the important URLs on every deploy
A full crawl is too slow for every commit. Instead, keep a short list of URLs that must keep working: top landing pages, URLs with many inbound links, and every old URL in your redirect map. Check them in CI and fail the build when something regresses.
Store the expectations in a file so that a change to a redirect is a reviewable change to data. This example uses a CSV with the URL path, the expected status, and the expected final path.
path,expected_status,expected_final
/,200,/
/pricing,200,/pricing
/old-page,301,/new-page
/retired-product,410,The next script reads that file, requests each URL without following redirects, and exits with a non-zero code if any expectation fails. A non-zero exit code is what makes a CI job fail.
import csv
import sys
from urllib.parse import urljoin, urlparse
import requests
BASE = sys.argv[1] if len(sys.argv) > 1 else "https://example.com"
EXPECTATIONS = sys.argv[2] if len(sys.argv) > 2 else "expectations.csv"
def check(row):
url = urljoin(BASE, row["path"])
resp = requests.get(url, allow_redirects=False, timeout=10, stream=True)
resp.close()
problems = []
expected_status = int(row["expected_status"])
if resp.status_code != expected_status:
problems.append(f"status {resp.status_code}, expected {expected_status}")
elif row["expected_final"]:
location = resp.headers.get("Location", "")
final_path = urlparse(urljoin(url, location)).path
if final_path != row["expected_final"]:
problems.append(f"redirects to {final_path}, expected {row['expected_final']}")
return url, problems
def main():
failures = 0
with open(EXPECTATIONS, newline="") as handle:
for row in csv.DictReader(handle):
url, problems = check(row)
if problems:
failures += 1
print(f"FAIL {url}: {'; '.join(problems)}")
else:
print(f"ok {url}")
sys.exit(1 if failures else 0)
if __name__ == "__main__":
main()This script checks only the first hop. If the first hop points to a URL that itself redirects, the chain goes unnoticed. To catch that, also request the expected final URL and assert that it returns 200 directly.
Wire the check into CI
Any CI system can run the script. This GitHub Actions workflow runs it after a deployment finishes and on a nightly schedule. The nightly run catches problems that appear without any code change, such as a rule edited by hand on the server.
name: link-health
on:
workflow_dispatch:
schedule:
- cron: "0 3 * * *"
workflow_run:
workflows: ["deploy"]
types: [completed]
jobs:
smoke:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install requests
- run: python check_urls.py https://example.com expectations.csvSchedule full crawls
A scheduled crawl finds what a short list cannot: internal links to deleted pages, external links that have rotted, and chains that grew over time. Run a crawl weekly for most sites and nightly for large or fast-changing ones. Keep the previous result and compare, because the useful signal is what is new since last time.
When you review a crawl, sort the findings in this order:
- New internal links to 404 or 410 pages, since you control the source.
- New redirect chains of two or more hops, and any loop.
- Pages that return 5xx errors, which may be intermittent.
- Broken external links on pages that receive traffic.
External link checks produce false alarms. Some sites block automated requests and return 403 or 429 to crawlers. Retry failures once after a delay, and treat a link as broken only after it fails on more than one run.
Watch real traffic
Crawlers only see links they can reach. Real users and bots request URLs from old bookmarks, other sites, and emails. Two sources show those requests.
The access log shows every failed request. This command reports the most requested paths that returned 404, and you can run it from cron and mail yourself the output.
awk '$9 == 404 {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20A path that appears here many times and has a clear replacement deserves a redirect. A path with a handful of requests from scanners, such as /wp-login.php on a site that does not use WordPress, deserves nothing. Do not redirect junk requests.
Search Console reports crawl errors, pages it considers soft 404s, and pages with redirect problems. Review it monthly, and look at the trend rather than a single day. A sudden rise after a release points to that release.
Treat redirects as permanent assets
Redirects from an old URL should last as long as anyone might still request that URL. Search engines and external sites can keep using an old address for years. Removing a rule because it looks old turns a working redirect into a new 404.
Good habits:
- Keep redirect rules in version control, with a comment explaining why each exists.
- Never delete a rule without checking the logs for recent requests to its source URL.
- When a redirect target changes, update every rule that pointed to the old target so that chains do not form.
- Return 410 for content that is gone with no replacement, and keep that rule in place too.
Collapsing chains is an ongoing job. When you move /b to /c, and /a already redirected to /b, change the rule for /a to point directly at /c. You can detect missed cases with the one-line curl summary.
curl -sL -o /dev/null -w '%{num_redirects} redirects, final status %{http_code}, final URL %{url_effective}\n' https://example.com/old-pageA result above 1 redirect is a chain to collapse.
Prevent breakage at the source
Fixing links after the fact is slower than stopping bad links from being published.
- Use your CMS's internal link feature where one exists, so links follow a page when its slug changes.
- Warn before delete or slug change. Many CMSs and static site generators can list pages that link to the one being changed. Make the editor handle those first.
- Require a redirect with a slug change. Make it part of the same pull request or content workflow, so the old URL never exists without a redirect.
- Use relative or root-relative internal links and avoid hard-coded absolute URLs with the wrong protocol or host.
- Lint links in the repository. For static sites, a link checker over the built output in CI fails the build before the broken link ships.
Common mistakes
- Monitoring only the home page. Failures usually happen deeper in the site.
- Alerting on every external failure. This trains people to ignore alerts. Alert on internal 404s, 5xx errors, and loops, and report external rot in a weekly digest.
- Checking with a browser only. Browsers cache 301 responses, so a stale redirect can look correct on your machine while a fresh client sees something else. Test with
curl. - Forgetting non-page URLs such as images, PDFs, and downloads.
- Letting the checker follow redirects silently, which hides the first-hop status you need to assert.
Exercise
A teammate renames /guides/setup to /docs/setup in a pull request. Your CI check passes, but two weeks later Search Console reports a rise in 404 errors for /guides/setup. List two likely causes in your process and one change for each.
Show answer
Likely cause 1: no redirect was added in the same change, and the CI expectations file did not include /guides/setup, so nothing asserted that the old URL redirects. Change: require a redirect and an entry in expectations.csv (301 to /docs/setup) whenever a URL is renamed. Likely cause 2: a redirect existed but was later removed or overwritten during config cleanup, and no scheduled check noticed. Change: keep redirects in version control with comments, run the expectations check nightly as well as on deploy, and check the access log for recent requests before deleting any rule.
Exercise
Your nightly crawl reports 300 broken external links, and the team has started ignoring the alert. How would you change the reporting?
Show answer
Separate internal from external findings. Alert immediately on internal 404s, 5xx errors, and redirect loops, since the team controls the fix. Retry external failures after a delay, ignore 403 and 429 responses from sites that block crawlers, and treat an external link as broken only after it fails on repeated runs. Send the remaining external failures as a weekly digest, ordered by the traffic of the page that contains the link.