In short
Google accepts three ways to declare a page's language versions: <link> tags in the HTML, the HTTP Link header and the XML sitemap. Many sites use two without knowing it, for example a multilingual plugin in the <head> and a sitemap that adds its own annotations. If you combine several methods, they must describe exactly the same groups, with the same URLs and the same codes. Once the task is done, an automated check compares the three sources and finds no discrepancy.
Why it matters
Google considers the three methods equivalent and states that using all three at once brings no benefit in search. Combining two methods is therefore never a gain, only one more risk.
This risk is real because the sources are often produced by different systems: the theme or multilingual plugin for the HTML, the SEO plugin or a nightly script for the sitemap, a server or CDN rule for the headers. As soon as a slug changes, a translation is unpublished or a code switches from en to en-GB, one of the sources follows and the other does not.
Google does not document how it decides between two contradictory declarations for the same page. Rather than guess, the safe rule is simple: a single method whenever possible, and otherwise several methods generated by the same function and checked regularly.
What it improves
- Readable groups The search engine receives a single version of the facts, whichever source it reads first.
- Maintenance A single place to fix, or at least a single function.
- Early detection A discrepancy between sitemap and HTML is often the first symptom of an unpublished translation or a changed slug.
- Rankings No direct effect. hreflang chooses which version to serve.
How to check
Start with an inventory of the methods actually in use, on a translated page:
# 1. Tags in the HTML
curl -s https://example.com/fr/tarifs/ | grep -o '<link[^>]*hreflang[^>]*>'
# 2. HTTP header
curl -s -D - -o /dev/null https://example.com/fr/tarifs/ | grep -i '^link:'
# 3. Sitemap
curl -s https://example.com/sitemap.xml | grep -c 'xhtml:link'
If the main sitemap is an index, open one of the sitemaps it lists. A count above zero means the sitemap carries annotations.
Expected result: a single method in use, or several that return exactly the same code/URL pairs for each page. To compare them across the whole site, use the script in step 3.
How to implement
Step 1 — Take inventory by content type
Fill in this table for each template (home page, pages, posts, products, categories, PDFs):
| Content type | HTML <link> |
Link header |
Sitemap xhtml:link |
What generates it? |
|---|---|---|---|---|
| Pages | yes | no | yes | Polylang (HTML), Yoast SEO (sitemap) |
| Products | yes | no | yes | Shopify (both) |
| PDFs | no | yes | no | Nginx rule |
| Blog posts | yes | no | no | Polylang |
A row with two “yes” values generated by two different tools should be handled first.
Step 2 — Choose a single source
Three cases:
- A single method is enough: this is the most robust choice. HTML tags for pages, HTTP headers for non-HTML files. The sitemap is preferable for very large sites, where dozens of tags would weigh down every page.
- The platform imposes two methods (Shopify, Webflow, some WPML configurations): they come from the same engine and normally stay aligned. Simply check them.
- Two methods from two different tools: turn one off, or rewrite them so that they call the same function (examples below).
Warning: do not remove a method before checking that the other covers every page. Removing the HTML tags when the sitemap does not include blog posts, for example, leaves them without annotations.
Step 3 — Compare the three sources automatically
This Python script (standard library only) reads a sitemap, fetches each URL, and compares the sitemap, HTML and HTTP header annotations for each one. Save it as comparer_hreflang.py:
import re
import sys
import urllib.request
import xml.etree.ElementTree as ET
from html.parser import HTMLParser
NS = {
"sm": "http://www.sitemaps.org/schemas/sitemap/0.9",
"xhtml": "http://www.w3.org/1999/xhtml",
}
def fetch(url):
request = urllib.request.Request(url, headers={"User-Agent": "hreflang-check"})
with urllib.request.urlopen(request, timeout=20) as response:
return response.headers.get_all("Link") or [], response.read()
class HeadParser(HTMLParser):
def __init__(self):
super().__init__()
self.found = set()
self.in_body = False
def handle_starttag(self, tag, attrs):
if tag == "body":
self.in_body = True
attributes = dict(attrs)
rel = (attributes.get("rel") or "").lower().split()
if tag == "link" and not self.in_body and "alternate" in rel and attributes.get("hreflang"):
self.found.add((attributes["hreflang"].lower(), attributes.get("href", "")))
def from_html(body):
parser = HeadParser()
parser.feed(body.decode("utf-8", "replace"))
return parser.found
def from_headers(values):
found = set()
for value in values:
for href, params in re.findall(r"<([^>]+)>\s*;([^<]*)", value):
rel = re.search(r'rel="?([^";,]+)', params)
lang = re.search(r'hreflang="?([^";,]+)', params)
if rel and lang and "alternate" in rel.group(1).lower().split():
found.add((lang.group(1).lower(), href))
return found
def from_sitemap(sitemap_url):
_, body = fetch(sitemap_url)
pages = {}
for url in ET.fromstring(body).findall("sm:url", NS):
loc = url.findtext("sm:loc", namespaces=NS).strip()
pages[loc] = {
(link.get("hreflang").lower(), link.get("href"))
for link in url.findall("xhtml:link", NS)
if link.get("rel") == "alternate" and link.get("hreflang")
}
return pages
def main(sitemap_url):
gaps = 0
for loc, in_sitemap in from_sitemap(sitemap_url).items():
try:
headers, body = fetch(loc)
except Exception as error:
print(f"ERROR {loc}: {error}")
continue
sources = {"sitemap": in_sitemap, "html": from_html(body), "http": from_headers(headers)}
used = {name: found for name, found in sources.items() if found}
reference = next(iter(used.values()), set())
if all(found == reference for found in used.values()):
print(f"OK {loc} ({', '.join(used) or 'no annotations'})")
continue
gaps += 1
print(f"GAP {loc}")
for lang, href in sorted(set().union(*used.values())):
present = [name for name, found in used.items() if (lang, href) in found]
if len(present) < len(used):
print(f" {lang:<10} {href} only present in: {', '.join(present)}")
print(f"{gaps} page(s) with discrepancies.")
if __name__ == "__main__":
main(sys.argv[1])
Run it on each page sitemap (not on the index):
python3 comparer_hreflang.py https://example.com/sitemap-pages-fr.xml
Reading the result:
OK … (sitemap, html): two methods, identical;GAPfollowed byonly present in: htmllines: the HTML announces a version that the sitemap ignores, or the other way round;- the same language listed twice with two different URLs: one source has kept the old slug or the pre-redirect URL.
The script reads the page as the server returns it, without executing JavaScript: tags added in the browser are not included, and that is intentional. Preferably run it on a sample (a few hundred URLs) and space out requests on a fragile server.
Step 4 — Run the same check with Screaming Frog
Without a script, Screaming Frog reads all three methods. Enable hreflang storage and crawling (Configuration > Spider), crawl the site, then crawl the sitemap in list mode: the sitemap hreflang columns are only filled in that mode. Export both Hreflang tabs and compare them in a spreadsheet, by URL and by code.
Check formula, with the concatenated code/URL pairs in column C of the html sheet and in column C of the sitemap sheet:
=IF(COUNTIF(sitemap!C:C,C2)=0,"missing from sitemap","ok")
Step 5 — Align generation
Fix at the source, then rerun the comparison. Examples by environment below.
WordPress
Versions WordPress 6.4 to 7.1; WPML 4 and 5 with WPML SEO, Polylang 3, Yoast SEO and Rank Math, November 2026.
- Polylang or WPML with Yoast SEO or Rank Math: these SEO plugins' sitemaps generally list the URLs of each language, without necessarily carrying hreflang annotations. Check with the
xhtml:linkcount command: if there are none, only the HTML method is in play. - WPML SEO: according to the WPML documentation, when this module adds the annotations to the sitemap, it can turn off their output in the
<head>, and turn it back on if the SEO plugin's sitemap is disabled. Check which method is active after each update. - Two multilingual plugins, or one plugin plus Weglot: keep only one.
Shopify
Versions Shopify admin, all plans, November 2026.
Shopify produces both the HTML tags, through content_for_header, and sitemaps that include the published languages, from the same market and language settings. The risk comes from additions: tags written in theme.liquid, an hreflang app or a translation app that adds its own tags. Remove them, or turn off the automatic hreflang tags option in Online Store > Preferences, in the SEO settings section, if you manage everything yourself.
Webflow
Versions Webflow Localization, site plans with localization, November 2026.
Webflow Localization generates the annotations in the pages and in the automatically generated sitemap. If you have replaced the sitemap with a custom sitemap or added tags in the site's custom code, remove them or turn off automatic generation, so as to keep a single source.
Next.js
Versions Next.js 15 and 16 (App Router).
Write a single function that returns a page's published versions, and call it from generateMetadata and from app/sitemap.ts:
// lib/alternates.ts
import { getPublishedTranslations } from '@/lib/cms'
export async function getLanguageAlternates(locale: string, slug: string): Promise<Record<string, string>> {
const translations = await getPublishedTranslations(locale, slug)
return Object.fromEntries(
translations.map((t) => [t.hreflang, `https://example.com${t.path}`]),
)
}
// app/sitemap.ts
import type { MetadataRoute } from 'next'
import { getAllPages } from '@/lib/cms'
import { getLanguageAlternates } from '@/lib/alternates'
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const pages = await getAllPages()
return Promise.all(
pages.map(async (page) => ({
url: `https://example.com${page.path}`,
lastModified: page.updatedAt,
alternates: { languages: await getLanguageAlternates(page.locale, page.slug) },
})),
)
}
In the page, use alternates: { languages: await getLanguageAlternates(locale, slug) }. The same set is output in the <head> and in the sitemap, self-reference included. The Next.js documentation example for localized sitemaps does not include the URL's own language in languages: add it.
Laravel
Versions Laravel 11 to 13.
Same principle: a model method, for example Page::hreflangAlternates(), called by the Blade component in the <head> and by the command that generates the sitemap. Generate the sitemap with the same APP_URL value as the site, otherwise the domain or protocol differs between the two sources.
Nginx
Versions Nginx 1.18 and later.
If an hreflang Link header is set by the server on HTML pages that already carry tags, remove it: keep headers for PDFs and other non-HTML files. Look for it with grep -rn "hreflang" /etc/nginx/. See use HTTP headers for PDFs if needed (opens in a new tab).
Cloudflare
Versions Cloudflare dashboard, all plans, November 2026.
A Response Header Transform Rule can add an hreflang Link without the team managing the CMS knowing. Review the rules from the Rules overview and delete those that duplicate the HTML tags.
Step 6 — Monitor
Schedule the script from step 3 every week, or after each deployment, and raise an alert as soon as it finds a discrepancy. See automate hreflang and canonical tests (opens in a new tab).
Common mistakes
- Not realizing a second method exists: the sitemap generated by a plugin carries annotations nobody looks at.
- Different URLs for the same page: with or without a trailing slash,
httpversushttps, a staging domain in the sitemap. - Different codes:
enin the HTML,en-GBin the sitemap, orx-defaultpresent in only one source. - Sitemap regenerated overnight, HTML immediately: for a few hours after each publication, the two sources diverge. Regenerate the sitemap on publication.
- Comparing after JavaScript execution: tags injected in the browser hide the absence of tags in the served HTML.
- Removing a method without checking the coverage of the other: entire templates end up without annotations.
Frequently asked questions
Can you use hreflang in the HTML and in the sitemap at the same time?
Yes, it is allowed, but Google states that combining methods brings no benefit in search: HTML tags, HTTP headers and the sitemap are equivalent as far as it is concerned. If you keep two methods, they must announce exactly the same URLs with the same codes, for every page. The safest approach is to generate them with the same function and compare them automatically after each deployment.
What does Google do if the sitemap and the HTML contradict each other?
Google does not document how it decides between two contradictory hreflang declarations for the same page. So you should not count on any specific behavior. An inconsistency may lead it to ignore part of the group or to serve an unexpected version. The only reliable answer is to eliminate the discrepancy: keep one method, or have both generated from the same data source.
Which hreflang method should you choose: HTML, HTTP header or sitemap?
HTML tags in the head suit most sites and are easy to check page by page. The sitemap suits very large sites, where dozens of tags would weigh down every page, and teams that have their generation under control. The HTTP header is reserved for files without a head, such as PDFs. Choose according to your tool: the best method is the one your CMS generates automatically and correctly.
Resources
- Google Search Central: tell Google about localized versions of your pagedevelopers.google.com
- Next.js: localized sitemap and generateMetadata, alternatesnextjs.org
- Shopify: hreflang and marketshelp.shopify.com
- Screaming Frog: how to audit hreflangscreamingfrog.co.uk
- Python: xml.etree.ElementTree and html.parserdocs.python.org
Updated on
Topic checklist (PDF)