Hreflang annotations, in this context, are the` tags that tell Google which pages are regional or language versions of each other. They're easy to write and easy to break. Google only uses a relationship if both pages point to each other: "If two pages don't both point to each other, the tags will be ignored" (Google Search Central). One stale URL in one market silently disconnects a whole group.
This post builds a small Python checker that reads the hreflang tags on a list of pages, follows every alternate, and flags the mistakes that show up most often in real sites:
- missing self-references
- missing return links
- invalid or suspicious codes (including the classic
en-UK) - alternate URLs that aren't fully qualified
- alternates that redirect, 404 or are canonicalised elsewhere
- a page whose own canonical points somewhere else
It uses requests and the standard library, and caches every fetch so each URL is requested once.
Setup
bash
pip install requests
Create urls.txt with one URL per line: one page from each regional version of your most important templates.
The script
`python
import re
import sys
from html.parser import HTMLParser
from urllib.parse import urljoin
import requests
HEADERS = {"User-Agent": "hreflang-check/1.0"}
CODE = re.compile(r"^[a-z]{2,3}(-[a-z]{4})?(-([a-z]{2}|\d{3}))?$", re.I)
class HeadParser(HTMLParser):
def init(self):
super().init()
self.alternates = {}
self.canonical = None
def handle_starttag(self, tag, attrs):
if tag != "link":
return
a = {k.lower(): (v or "") for k, v in attrs}
rel = a.get("rel", "").lower().split()
if "alternate" in rel and "hreflang" in a:
self.alternates[a["hreflang"]] = a.get("href", "")
elif "canonical" in rel:
self.canonical = a.get("href")
def fetch(url, cache):
if url not in cache:
r = requests.get(url, headers=HEADERS, allow_redirects=False, timeout=20)
page = HeadParser()
if r.status_code == 200:
page.feed(r.text)
cache[url] = (r.status_code, page)
return cache[url]
def check(url, cache):
problems = []
status, page = fetch(url, cache)
if status != 200:
return [f"page returns {status}"]
if not page.alternates:
return ["no hreflang annotations"]
if page.canonical and urljoin(url, page.canonical) != url:
problems.append(f"canonical points elsewhere: {page.canonical}")
if url not in page.alternates.values():
problems.append("no self-reference")
for code, href in page.alternates.items():
if code.lower() == "x-default":
continue
if not CODE.match(code):
problems.append(f"invalid code '{code}'")
elif code.lower().endswith("-uk"):
problems.append(f"'{code}' uses UK; the region code is GB")
for code, href in page.alternates.items():
if not href.startswith(("http://", "https://")):
problems.append(f"{code}: URL not fully qualified ({href})")
continue
if href == url:
continue
alt_status, alt = fetch(href, cache)
if alt_status != 200:
problems.append(f"{code}: {href} returns {alt_status}")
continue
if alt.canonical and urljoin(href, alt.canonical) != href:
problems.append(f"{code}: {href} is canonicalised elsewhere")
if url not in alt.alternates.values():
problems.append(f"{code}: no return link from {href}")
if "x-default" not in {c.lower() for c in page.alternates}:
problems.append("note: no x-default")
return problems
def main(urls):
cache, failures = {}, 0
for url in urls:
problems = check(url, cache)
real = [p for p in problems if not p.startswith("note:")]
print(f"{'OK ' if not real else 'FAIL'} {url}")
for p in problems:
print(f" {p}")
failures += bool(real)
print(f"\n{len(urls) - failures}/{len(urls)} pages passed")
sys.exit(1 if failures else 0)
if name == "main":
main([line.strip() for line in open(sys.argv[1]) if line.strip()])
`
How it works
HeadParser collects every link element with rel="alternate" and an hreflang attribute, keyed by code, plus the canonical URL. It splits rel into tokens, so rel="alternate nofollow" still works.
fetch requests each URL once with allow_redirects=False and caches the result. Not following redirects is deliberate: an hreflang alternate that redirects is a problem worth reporting, because Google expects the final, canonical URL in the annotation.
check runs the tests for one page:
- The page must return
200and contain hreflang annotations. - Its canonical must point to itself. Regional versions should be self-canonical.
- It must reference itself.
- Every code must look like a valid language(-script)(-region) code.
en-UKgets a special message because it's the most common mistake on UK sites: the United Kingdom's ISO code isGB. - Every alternate URL must be fully qualified. Google requires it: alternate URLs "must be fully-qualified, including the transport method (http/https)".
- Every alternate must return
200, be self-canonical, and link back.
x-default is reported as a note rather than a failure, because it's recommended rather than required.
A test run
I built a small four-market test site locally, with deliberate mistakes in three of the four pages, and ran the checker against it:
`text
FAIL http://127.0.0.1:8765/uk/service/
en-US: http://127.0.0.1:8765/us/service/ is canonicalised elsewhere
en-AE: no return link from http://127.0.0.1:8765/ae/service/
FAIL http://127.0.0.1:8765/us/service/
canonical points elsewhere: http://127.0.0.1:8765/uk/service/
FAIL http://127.0.0.1:8765/ae/service/
'en-UK' uses UK; the region code is GB
en-UK: http://127.0.0.1:8765/uk-old/ returns 404
en-US: http://127.0.0.1:8765/us/service/ is canonicalised elsewhere
en-AU: URL not fully qualified (/au/service/)
note: no x-default
FAIL http://127.0.0.1:8765/au/service/
no self-reference
en-US: http://127.0.0.1:8765/us/service/ is canonicalised elsewhere
en-AE: no return link from http://127.0.0.1:8765/ae/service/
note: no x-default
0/4 pages passed
`
Notice how one mistake spreads. The US page's canonical points to the UK page, so every other market reports the US alternate as "canonicalised elsewhere". The UAE page points to an old UK URL, so the UK page reports a missing return link from the UAE. Fix the two source errors and several downstream messages disappear.
After correcting the pages, the same run reports 4/4 pages passed and exits with 0.
Reading the output
The messages fall into three groups, and it helps to fix them in this order:
- Page-level problems such as a canonical pointing elsewhere or a missing self-reference. These usually come from a template, and fixing one template often fixes a whole market.
-
Broken alternates that return
404or redirect. These normally mean URLs changed without the hreflang being updated. The fix is to point the annotation at the new final URL, not to rely on the redirect. - Missing return links. Check these last. Many of them disappear once the first two groups are fixed, because they're symptoms of a page that is broken or canonicalised elsewhere.
Codes deserve a special mention. The regular expression accepts any well-formed language and region pattern, so it won't catch a valid code used for the wrong market, such as en-AU on the New Zealand pages. The -uk check exists because that particular mistake is so common on British sites that it's worth a dedicated warning.
Why not just use a crawler?
Desktop SEO crawlers report hreflang issues well, and for a one-off audit they're often the better tool. A script earns its place in automation: it runs in CI, checks a known set of pages on every release, and fails the build when something breaks. The two work well together, with the crawler for periodic deep checks and the script as a fast guard rail.
Running it on a schedule
Because the script exits with 1 when any page fails, it drops straight into CI. A scheduled job that installs requests and runs python check_hreflang.py urls.txt once a week, and after deployments that touch templates or URLs, will catch most regressions within days rather than months.
Keep urls.txt focused: one example per template per market is usually enough, because hreflang is almost always generated by templates. If one product page is wrong, they all are.
Things to watch out for
-
Sitemap-based hreflang. This script reads HTML
linktags. If your annotations live in an XML sitemap, parse thexhtml:linkelements from the sitemap instead; the checks stay the same. -
Trailing slashes and protocol. The script compares URLs exactly, so
https://example.com/au/serviceandhttps://example.com/au/service/are different. That's intentional: hreflang should use the exact canonical URL. -
Bot protection. CDNs that challenge unknown user agents will return
403. Allow-list the checker. - Equivalence. The script checks that relationships are technically valid, not that the pages are genuinely equivalent. A UK service page linked to an unrelated US page will pass. A human still needs to review the map.
Extending it
- Read the expected groups from your hreflang spreadsheet and compare them with what's live.
- Check that the
htmlelement'slangattribute matches the page's own hreflang code. - Output a CSV of every relationship for review by non-developers.
- Add a check that each regional page is actually indexable (no
noindex, not blocked by robots.txt).
Where this fits
Validation catches breakage. Designing the setup properly in the first place is the bigger job, and this is a good companion read: a practical guide to hreflang for UK, US, UAE and Australian sites.
Put one URL per template per market in urls.txt, run the checker, and fix the source errors first. The downstream messages usually take care of themselves.
Top comments (0)