Hreflang tells Google which URL to show to searchers in each language or region when you have equivalent pages in several languages. You can implement hreflang in three ways: <link rel="alternate" hreflang="..."> tags in the HTML <head>, an HTTP Link header, or <xhtml:link> entries in an XML sitemap. Whichever you pick, every page in a set must list itself and every alternate, using ISO 639-1 language codes with optional ISO 3166-1 region codes, and every alternate must link back.

That summary hides most of what goes wrong in practice. In my audits, the hreflang syntax is usually fine; the failures come from return links that point at redirecting URLs, canonicals that point across languages, and region codes like en-UK that Google silently ignores. This guide covers the three methods, the code rules, x-default, reciprocity, canonical interplay and the errors audit tools report, with a tested generator script for sitemap hreflang. Rules are quoted from Google's localized versions documentation (last updated 21 September 2026), checked in December 2026.

What hreflang does, and what it does not do

Hreflang is a URL-swapping hint. When Google ranks a page from your site for a query, and that page belongs to an hreflang cluster, Google can show the alternate that matches the searcher's language and location instead. A German searcher in Switzerland sees /ch-de/preise/, a British one sees /uk/pricing/.

What it does not do:

  • It does not make a page rank. It chooses which member of a cluster to show. If none of the cluster ranks, hreflang has nothing to swap.
  • It does not tell Google what language a page is in. Google detects language from the visible content and does not use lang attributes or the URL for that.
  • It is not a fix for duplicate content. Equivalent pages in the same language for different regions (en-US, en-GB, en-AU) can still be folded together if they are near-identical. Give regional pages genuinely regional content: prices, currency, shipping, legal text, spelling.
  • It does not override geotargeting signals entirely. Google lists ccTLDs, hreflang and server location among the signals it uses to work out a page's audience.

The three ways to implement hreflang

Google treats the three methods as equivalent. Pick the one you can keep correct, and use only one: mixing methods gives no extra benefit and creates two sources of truth that will eventually disagree.

Method Best for Main drawback
HTML <link> tags Small and mid-sized sites, CMS templates Adds bytes to every page; every template must stay in sync
HTTP Link header PDFs and other non-HTML files Hard to inspect and maintain; easy to break at the CDN
XML sitemap Large sites, many languages, headless setups Nothing visible on the page; sitemap must be regenerated when URLs change

Each language version carries the full set of <link> elements, including one pointing at itself. The set is identical on every page in the cluster:

<head>
  <link rel="canonical" href="https://www.example.com/de/preise/">
  <link rel="alternate" hreflang="en"        href="https://www.example.com/pricing/">
  <link rel="alternate" hreflang="en-GB"     href="https://www.example.com/uk/pricing/">
  <link rel="alternate" hreflang="de"        href="https://www.example.com/de/preise/">
  <link rel="alternate" hreflang="de-CH"     href="https://www.example.com/ch-de/preise/">
  <link rel="alternate" hreflang="x-default" href="https://www.example.com/pricing/">
</head>

Put the tags in the server-rendered <head>. Two practical gotchas. First, Google stops reading the <head> at the first invalid element (anything other than title, meta, link, script, style, base, noscript or template), so a stray <img> or <iframe> injected by a tag manager above your hreflang block makes Google ignore it. Second, frameworks that inject hreflang only on the client make you depend on rendering. Render them on the server.

At 20 or more languages, the tag block gets long. A page with 40 alternates carries 40 extra lines on every request. At that point the sitemap method is usually cleaner.

Use this for non-HTML files such as PDFs. The header lists every version, including the requested one, separated by commas, and is identical for every version:

HTTP/1.1 200 OK
Content-Type: application/pdf
Link: <https://www.example.com/docs/guide.pdf>; rel="alternate"; hreflang="en",
      <https://www.example.com/de/docs/leitfaden.pdf>; rel="alternate"; hreflang="de",
      <https://www.example.com/docs/guide.pdf>; rel="alternate"; hreflang="x-default"

The header is a single line on the wire; it is wrapped here for readability. In nginx, add_header Link '<...>; rel="alternate"; hreflang="en", <...>; ...'; inside the relevant location block does the job, but remember that add_header directives in a nested block replace, rather than add to, those inherited from the parent. Verify with curl -sI https://www.example.com/docs/guide.pdf | grep -i '^link' after every deploy.

Method 3: hreflang in the XML sitemap

Each <url> entry lists all alternates, including itself, using the xhtml namespace. Every member of the cluster gets its own <url> entry with the same set of links:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <url>
    <loc>https://www.example.com/pricing/</loc>
    <xhtml:link rel="alternate" hreflang="en" href="https://www.example.com/pricing/"/>
    <xhtml:link rel="alternate" hreflang="de" href="https://www.example.com/de/preise/"/>
    <xhtml:link rel="alternate" hreflang="x-default" href="https://www.example.com/pricing/"/>
  </url>
  <url>
    <loc>https://www.example.com/de/preise/</loc>
    <xhtml:link rel="alternate" hreflang="en" href="https://www.example.com/pricing/"/>
    <xhtml:link rel="alternate" hreflang="de" href="https://www.example.com/de/preise/"/>
    <xhtml:link rel="alternate" hreflang="x-default" href="https://www.example.com/pricing/"/>
  </url>
</urlset>

The sitemap method scales best and keeps page weight down, which is why I default to it on any site with more than a handful of languages. The cost is that hreflang problems are invisible when you look at a page, so you need a check in CI (there is one later in this guide). The usual sitemap limit of 50,000 URLs per file still applies, and the alternate links inflate the file size quickly.

Language and region codes: the rules that trip people up

An hreflang value is a language code, optionally followed by a region:

  • Language: ISO 639-1, two letters: en, de, pt.
  • Region (optional): ISO 3166-1 Alpha 2, two letters: en-GB, pt-BR, es-MX.
  • Script (optional): ISO 15924 for script variants: zh-Hans, zh-Hant, or with a region, zh-Hans-US. For zh-TW, Google derives Traditional Chinese automatically.
  • Case: values are case-insensitive. Uppercase regions are just convention.

The mistakes I see most often, all of which Google documents:

Wrong Why it fails Use instead
en-UK UK is a reserved code; Google ignores it en-GB
be for Belgium be is the Belarusian language nl-BE, fr-BE, de-BE
GB, US alone Region-only codes are invalid en-GB, en-US
es-419 (Latin America) Not ISO 3166-1 Alpha 2; unsupported es plus specific es-MX, es-AR…
en-EU, en-UN Reserved codes are ignored One code per country, or plain en
en_GB Underscore is not valid syntax en-GB

The es-419 case deserves a note, because many CMSs and translation platforms default to it. If you have one Spanish version for all of Latin America and another for Spain, label the Spain page es-ES and the Latin American page plain es. The es page then acts as the catch-all for every Spanish speaker not in Spain.

That catch-all idea generalises. Google recommends a language-only version whenever you have several regional variants: if you target en-IE, en-CA and en-AU, also provide en (which can be one of those pages) for English speakers everywhere else.

x-default: the fallback for everyone else

hreflang="x-default" names the page to show when no other value matches the searcher's language settings. It was designed for language or country selector pages and works best there, but pointing it at your main-market page (usually the English version) is common and fine.

Rules worth remembering:

  • x-default takes no language code.
  • It goes in the same set as all the other alternates, on every page of the cluster.
  • The x-default URL can also appear under a language code. In the example above, /pricing/ is both en and x-default.
  • If your home page auto-redirects by IP or Accept-Language, the selector it falls back to is the natural x-default.

On auto-redirects: Google's guidance is to avoid redirecting users by perceived language or IP, partly because Googlebot usually crawls from the US and sends no Accept-Language header. Redirect Googlebot to /en-us/ every time and it may never see your other versions. Show a dismissible banner suggesting the local version instead.

Return tags: reciprocity is not optional

If page A lists page B as an alternate, page B must list page A. If it does not, Google may ignore the annotations. Google designed it this way so that a third-party site cannot claim to be an alternate of your pages.

In practice, "missing return link" errors rarely come from a forgotten tag. They come from URL mismatches. The return link exists but points at a slightly different URL:

  • https://www.example.com/de/preise vs https://www.example.com/de/preise/ (trailing slash, one of them redirects)
  • http:// vs https://, or example.com vs www.example.com
  • a URL with tracking parameters or a session ID
  • relative URLs (/de/preise/); hreflang URLs must be fully qualified, including the protocol

Generate hreflang from one canonical URL function in your code base, the same one that produces your canonical tags, and most of these disappear.

When maintaining every pairing becomes impractical (say 30 markets, launched over years), Google says it will still process the pairs that do point at each other, and advises linking new language versions bidirectionally to the dominant original version first.

Hreflang and canonical tags

Canonical and hreflang do different jobs and must agree:

  1. Every hreflang URL should be the canonical URL of its page. Each localized page carries a self-referencing canonical. Never point the German page's canonical at the English page; that tells Google the German page is a duplicate to be dropped, and its hreflang goes with it.
  2. Never list a non-canonical URL in hreflang. If /de/preise/?ref=nav canonicalises to /de/preise/, only the latter belongs in the cluster.
  3. Canonical within the same language. Google's canonicalization documentation says that when you use hreflang you should specify a canonical in the same language, or the best substitute language if none exists.
  4. Don't use rel="canonical" with hreflang attributes. Google states that canonical annotations carrying hreflang, lang, media or type attributes are not used for canonicalization.

One helpful detail from the same documentation: Google prefers URLs that are part of hreflang clusters when choosing canonicals. Consistent clusters actively help your preferred URLs get picked.

To see what Google actually chose, run URL Inspection in Search Console on each localized URL and compare "User-declared canonical" with "Google-selected canonical". If Google picked the English page as canonical for your Australian page, the two are too similar; add genuinely local content. Localized pages that Google judges thin often end up in the Crawled – currently not indexed bucket, and no hreflang tag will rescue them.

Generate sitemap hreflang with a script

Hand-written hreflang does not survive the second language launch. This Python 3 script (standard library only; I ran it with Python 3.12) reads a CSV of translation clusters and writes valid sitemap XML, rejecting the code mistakes from the table above before anything ships.

The input is one row per language version:

group,hreflang,url
pricing,en,https://www.example.com/pricing/
pricing,en-gb,https://www.example.com/uk/pricing/
pricing,de,https://www.example.com/de/preise/
pricing,de-CH,https://www.example.com/ch-de/preise/
pricing,x-default,https://www.example.com/pricing/
about,en,https://www.example.com/about/
about,de,https://www.example.com/de/ueber-uns/
about,zh-hant-tw,https://www.example.com/zh-tw/about/
#!/usr/bin/env python3
"""Build hreflang XML sitemaps from a CSV of translation clusters.

CSV columns: group,hreflang,url  (one row per language version; use
hreflang "x-default" for the fallback). Usage:
    python3 hreflang_sitemap.py pages.csv sitemap-hreflang
"""
import csv, re, sys
from collections import defaultdict, OrderedDict
from xml.sax.saxutils import quoteattr, escape

CODE = re.compile(r'^[a-z]{2}(-[A-Z][a-z]{3})?(-[A-Z]{2})?$')  # ll, ll-RR, ll-Ssss, ll-Ssss-RR
RESERVED_REGIONS = {'UK', 'EU', 'UN'}                           # Google ignores these
MAX_URLS = 50_000                                               # per sitemap file

def normalise(code):
    if code.lower() == 'x-default':
        return 'x-default'
    parts = code.replace('_', '-').split('-')
    out = [parts[0].lower()]
    for p in parts[1:]:
        out.append(p.title() if len(p) == 4 else p.upper())
    return '-'.join(out)

def load(path):
    groups, errors = defaultdict(OrderedDict), []
    with open(path, newline='', encoding='utf-8') as f:
        for n, row in enumerate(csv.DictReader(f), start=2):
            code, url = normalise(row['hreflang'].strip()), row['url'].strip()
            if code != 'x-default':
                if not CODE.match(code):
                    errors.append(f'line {n}: invalid hreflang "{row["hreflang"]}"')
                elif code.split('-')[-1] in RESERVED_REGIONS:
                    errors.append(f'line {n}: reserved region in "{code}" (use en-GB, not en-UK)')
            if not url.startswith('https://'):
                errors.append(f'line {n}: URL must be absolute https: {url}')
            if code in groups[row['group']]:
                errors.append(f'line {n}: duplicate {code} in group {row["group"]}')
            groups[row['group']][code] = url
    for g, alts in groups.items():
        urls = [u for c, u in alts.items() if c != 'x-default']
        if len(set(urls)) != len(urls):
            errors.append(f'group {g}: one URL is mapped to two language codes')
    return groups, errors

def url_entries(groups):
    for alts in groups.values():
        links = ''.join(
            f'\n    <xhtml:link rel="alternate" hreflang={quoteattr(c)} href={quoteattr(u)}/>'
            for c, u in alts.items())
        for code, url in alts.items():
            if code == 'x-default' and url in [u for c, u in alts.items() if c != 'x-default']:
                continue                    # already emitted under its language code
            yield f'  <url>\n    <loc>{escape(url)}</loc>{links}\n  </url>\n'

def main(csv_path, prefix):
    groups, errors = load(csv_path)
    if errors:
        sys.exit('\n'.join(errors))
    entries = list(url_entries(groups))
    head = ('<?xml version="1.0" encoding="UTF-8"?>\n'
            '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"\n'
            '        xmlns:xhtml="http://www.w3.org/1999/xhtml">\n')
    for i in range(0, len(entries), MAX_URLS):
        name = f'{prefix}-{i // MAX_URLS + 1}.xml'
        with open(name, 'w', encoding='utf-8') as f:
            f.write(head + ''.join(entries[i:i + MAX_URLS]) + '</urlset>\n')
        print(f'wrote {name}: {len(entries[i:i + MAX_URLS])} URLs')

if __name__ == '__main__':
    main(*sys.argv[1:3])

Run against the sample CSV, it writes seven <url> entries (the x-default page is already listed as en), normalises en-gb to en-GB and zh-hant-tw to zh-Hant-TW, and the output passes xmllint --noout. Fed a CSV with en-UK, es-419 and an http:// URL, it refuses to write anything:

line 2: reserved region in "en-UK" (use en-GB, not en-UK)
line 3: invalid hreflang "es-419"
line 4: URL must be absolute https: http://a.example/de

The regex checks the shape of a code, not that xx is a real ISO 639-1 language; add a lookup table if your translators invent codes. Export the CSV from your CMS or translation management system, run this in CI, and reference the output files from your sitemap index. For the plain sitemap of a smaller site, the XML sitemap generator on this site is a quicker starting point.

Common hreflang errors and how to fix them

Search Console no longer reports hreflang errors. The International Targeting report was deprecated; Google says it continues to support and use hreflang, but there is no replacement report. Errors now come from crawlers such as Screaming Frog, Sitebulb or Ahrefs, which use slightly different names for the same problems. Screaming Frog, for example, only populates its hreflang checks when "Crawl Hreflang" and "Store Hreflang" are enabled, and reports issues such as missing return links, inconsistent language return links and non-canonical return links.

Audit error Usual root cause Fix
Missing return links Alternate page lacks the set, or links back to a variant URL Emit the identical set on every page from one URL function
Inconsistent language return links Page calls itself en-GB, partner calls it en Store one code per URL in one place
Non-200 hreflang URL Alternate redirects (trailing slash, http→https) or 404s List final 200 URLs only
Non-canonical return links Alternate's canonical points elsewhere Self-referencing canonicals on every localized URL
Noindex return links Alternate is noindex (often a staging leftover) Index it, or remove it from the cluster
Missing self-reference Template lists only other languages Include the current page in its own set
Incorrect language/region codes en-UK, es-419, region-only codes See the code table above
Multiple entries for one code Two URLs claim de in one cluster One URL per code per cluster
Missing x-default No fallback declared Optional, but add it for selector or main-market pages

For a quick check on live pages without a crawler licence, this script fetches a page, follows each alternate and checks status codes, canonicals and return links. It does not follow redirects, so a redirecting alternate is reported rather than silently accepted. I tested it against a local server with a deliberately broken cluster:

#!/usr/bin/env python3
"""Check hreflang return links, self-references and canonicals on live pages.
Usage: python3 hreflang_check.py https://www.example.com/pricing/ [more URLs...]
"""
import sys, urllib.request, urllib.error
from html.parser import HTMLParser

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None                                   # surface 3xx instead of following

OPENER = urllib.request.build_opener(NoRedirect)

class Head(HTMLParser):
    def __init__(self):
        super().__init__(); self.alts, self.canonical = {}, None
    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        rel = (a.get('rel') or '').lower().split()
        if tag == 'link' and 'alternate' in rel and a.get('hreflang'):
            self.alts[a['hreflang'].lower()] = a.get('href')
        elif tag == 'link' and 'canonical' in rel:
            self.canonical = a.get('href')

cache = {}
def fetch(url):
    if url not in cache:
        req = urllib.request.Request(url, headers={'User-Agent': 'hreflang-check/1.0'})
        try:
            with OPENER.open(req, timeout=15) as r:
                p = Head(); p.feed(r.read().decode('utf-8', 'replace'))
                cache[url] = (r.status, p.alts, p.canonical)
        except urllib.error.HTTPError as e:
            cache[url] = (e.code, {}, None)
    return cache[url]

def check(url):
    problems = []
    status, alts, canonical = fetch(url)
    if status != 200:
        return [f'{url} returned {status}']
    if canonical and canonical != url:
        problems.append(f'canonical points elsewhere ({canonical}); hreflang on a non-canonical URL is ignored')
    if url not in alts.values():
        problems.append('no self-referencing hreflang')
    my_codes = {c for c, u in alts.items() if u == url}
    for code, alt in alts.items():
        if alt == url:
            continue
        a_status, a_alts, a_canon = fetch(alt)
        if a_status != 200:
            problems.append(f'{code} -> {alt} returned {a_status}')
        elif a_canon and a_canon != alt:
            problems.append(f'{code} -> {alt} canonicalises to {a_canon}')
        elif url not in a_alts.values():
            problems.append(f'{code} -> {alt} has no return link to this page')
        elif code != 'x-default' and not my_codes & {c for c, u in a_alts.items() if u == url}:
            problems.append(f'{code} -> {alt} links back with a different code')
    return problems

if __name__ == '__main__':
    bad = 0
    for u in sys.argv[1:]:
        issues = check(u)
        bad += bool(issues)
        print(('OK   ' if not issues else 'FAIL ') + u)
        for i in issues:
            print('     - ' + i)
    sys.exit(1 if bad else 0)
FAIL http://127.0.0.1:8765/en/
     - fr -> http://127.0.0.1:8765/fr/ has no return link to this page
     - es -> http://127.0.0.1:8765/es returned 301
OK   http://127.0.0.1:8765/de/

It reads HTML <link> tags only; for header- or sitemap-based hreflang, adapt fetch() to parse the Link header or your sitemap instead.

Verify that the right version ranks

Clean tags are not the goal; the right URL in the right country is. Two checks in Search Console:

  1. In the Performance report, filter by Country and then group by Page. If German searchers mostly see your English URLs, the German pages either are not indexed or are not clustered. The guide to checking keyword rankings in Search Console covers those filters in detail.
  2. Run URL Inspection on a sample of localized URLs and compare declared and Google-selected canonicals.

Localized titles and meta descriptions matter here too. A German page with an English meta description often gets a Google-rewritten snippet; the meta description guide covers writing templates you can translate per market.

Frequently Asked Questions

Is hreflang a ranking factor?

No. Hreflang does not raise a page's ranking. It helps Google swap in the right language or regional version of a page that already ranks. A correct implementation can still improve click-through and conversions, because users land on a page in their own language with local prices.

Do I need hreflang if my site has only one language?

No. Hreflang is for sets of equivalent pages in different languages or for different regions. A single-language site with no regional variants gains nothing from it. Add a self-referencing canonical and move on.

Should I use HTML tags or the XML sitemap for hreflang?

Both work equally well for Google. Use HTML tags when you have a few languages and a templated CMS. Use the sitemap when you have many languages, a headless setup, or concerns about page weight. Do not use both; when they disagree, you have created your own errors.

What is the correct hreflang code for the United Kingdom?

en-GB. The UK region code is reserved and Google ignores it, so en-UK is effectively an untargeted annotation. The same applies to EU and UN.

Do hreflang tags need to point to the canonical URL?

Yes. Every URL in an hreflang set should be the indexable, canonical, 200-status version of that page. Pointing hreflang at redirects, noindexed pages or URLs whose canonical points elsewhere causes the annotations to be ignored.

Does Google still report hreflang errors in Search Console?

No. The International Targeting report that used to show hreflang errors has been deprecated, and there is no replacement. Use a crawler or a script like the one above to validate return links, codes and canonicals, and use URL Inspection to check canonical selection.

Conclusion

Hreflang is simple in syntax and fragile in practice. Choose one method (sitemaps for large sites, HTML tags for small ones), generate it from the same URL function as your canonicals, use valid ISO codes (en-GB, never en-UK), include a self-reference and an x-default, and make sure every alternate returns 200 with a self-referencing canonical and a matching return link. Then automate the check, because the implementation that is correct today breaks on the next URL migration.