In short
On a multilingual site, each page must declare its own language: <html lang="fr"> on /fr/tarifs/, <html lang="de"> on /de/preise/. The value must be determined by the requested URL and written into the HTML returned by the server, not inferred from a cookie, the browser language or a script run afterwards. Once the task is done, each language version announces the right language, whichever visitor or bot requests it. The basic setting, for a single-language site, is covered in check the lang attribute (opens in a new tab).
Why it matters
The lang attribute serves assistive technologies first. A screen reader picks its voice and pronunciation rules from it: a German page declared lang="fr" is read with French phonetics. WCAG success criterion 3.1.1 (Web Content Accessibility Guidelines, level A) requires that the language of each page can be programmatically determined.
The browser uses it too: automatic hyphenation (hyphens: auto), selection of language-specific glyphs in some fonts, language-sensitive capitalization (the Turkish i becomes İ), and the offer to translate the page.
On the search engine side, Google states that it determines the language of a page from its visible content, not from the lang attribute. Bing does not document precisely which signals it reads; industry tools say it takes lang and Content-Language into account, without official confirmation. A correct attribute therefore brings no ranking gain, but a wrong one muddles all the metadata: lang says one language, hreflang another, the content a third.
On a multilingual site, the typical error is not a missing attribute but a frozen value: the template writes the site's default language on every version, or the value depends on a cookie and changes with the visitor's last choice. In the second case, a bot without cookies sees lang="fr" on the German page, and a cache can serve one visitor's variant to everyone.
What it improves
- Accessibility Correct pronunciation of each version by screen readers and speech synthesis; compliance with WCAG criterion 3.1.1 in every language.
- Text rendering Hyphenation, typography and the browser's translation offer suited to each version.
- Consistent signals
lang, hreflang (opens in a new tab),og:localeand the content tell the same story, which avoids ambiguity for tools that read the code. - Audits Lighthouse and axe no longer flag a missing or invalid value.
- Google rankings No direct effect, Google detects the language from the content.
How to check
Read the <html> tag of one page per language, without cookies, and compare:
for url in https://example.com/fr/tarifs/ https://example.com/de/preise/ https://example.com/en/pricing/; do
printf '%s -> ' "$url"
curl -s "$url" | grep -o -i -m 1 '<html[^>]*>'
done
Expected result:
https://example.com/fr/tarifs/ -> <html lang="fr">
https://example.com/de/preise/ -> <html lang="de">
https://example.com/en/pricing/ -> <html lang="en">
Then run the test again while announcing another browser language, for example curl -s -H "Accept-Language: ja" https://example.com/de/preise/. The value must not change: it depends on the URL, not on the visitor.
Across the whole site:
- Screaming Frog: custom extraction with the XPath
/html/@lang, then export and sort by language folder. Any URL under/de/that does not returndeneeds fixing. - Consistency with hreflang: in the same crawl, extract
//link[@rel='alternate'][@href=//link[@rel='canonical']/@href]/@hreflangto get the hreflang value the page gives itself, and compare its language part withlang. - W3C Internationalization Checker: for a given URL, it shows the language declared by the attribute, by the
Content-Languageheader and by any meta tag. - Lighthouse, Accessibility category: it checks that the attribute is present and valid, not that it is correct. A German page marked
lang="fr"passes the audit.
Warning: test with curl or with a browser in private browsing. In your usual browser, a language cookie can hide the problem.
How to implement
Before you start
The rule. The page's language is derived from the URL: prefix (/de/), subdomain (de.example.com) or domain (example.de). The server resolves this language before generating the HTML and writes it into lang. Never from a cookie, a session or the Accept-Language header: see avoid handling language only through cookies/JS (opens in a new tab).
The mapping table. Document the value for each version once and for all:
| URL | lang |
hreflang |
og:locale |
|---|---|---|---|
/fr/ |
fr |
fr |
fr_FR |
/fr-ca/ |
fr-CA |
fr-CA |
fr_CA |
/de/ |
de |
de |
de_DE |
/ar/ |
ar (with dir="rtl") |
ar |
ar_AR |
lang and hreflang use the same BCP 47 syntax with a hyphen; og:locale uses an underscore. The region belongs in lang only if the text is genuinely adapted to that country.
The missing translation case. If a /de/ URL falls back to displaying the French text, lang must say fr, not de: it describes the language of the text. Better not to publish such pages at all, see plan for missing translations (opens in a new tab).
Right-to-left languages add dir="rtl" on the same tag: see handle dir=rtl if needed (opens in a new tab).
Apache
Versions Apache 2.4.
Apache does not write the attribute: the application or the HTML files carry it. For a static site, every file under /de/ must start with <html lang="de">.
You can additionally send the Content-Language HTTP header, which describes the intended audience. It is optional; if present, it must be consistent with lang. In the virtual host or .htaccess:
<IfModule mod_headers.c>
<If "%{REQUEST_URI} =~ m#^/de/#">
Header set Content-Language "de"
</If>
<ElseIf "%{REQUEST_URI} =~ m#^/en/#">
Header set Content-Language "en"
</ElseIf>
<Else>
Header set Content-Language "fr"
</Else>
</IfModule>
Reload with sudo apachectl configtest && sudo systemctl reload apache2.
Nginx
Versions Nginx 1.18 and later, including 1.30 (stable) and 1.31 (mainline).
Same principle: the attribute comes from the pages. For the optional header, declare a map in the http context:
map $uri $content_language {
~^/de/ de;
~^/en/ en;
default fr;
}
Then in the server block:
add_header Content-Language $content_language always;
By default, an add_header in a location block cancels those of the server block: repeat it where needed. Since Nginx 1.29.3 (and therefore in the 1.30 stable branch), add_header_inherit merge; in the location block also keeps the inherited headers. sudo nginx -t && sudo systemctl reload nginx.
WordPress
Versions WordPress 6.4 and later; Polylang 3, WPML 4 and 5, TranslatePress and Weglot, November 2026.
WordPress writes the attribute with language_attributes() in the theme header, based on the active locale. Multilingual plugins are what change this locale for each page:
- Polylang: the language of each piece of content is set in the editor's “Languages” box; the locale of each language (
de_DE) inLanguages > Languages. InLanguages > Settings, “URL modifications” module, choose the option where the language is set from the directory name in the URL, not from the content. - WPML: the URL format is set in
WPML > Settings, URLs and SEO section, since WPML 5 (inWPML > Languageswith WPML 4). Choose a directory per language or a domain per language. Avoid the?lang=parameter. - TranslatePress, Weglot: they rewrite the language according to the URL prefix. Check one page per language with the command from the “How to check” section.
Check that the theme's header.php does contain <html <?php language_attributes(); ?>>, with no hard-coded value. If the cache plugin serves the same page to every language, see check per-language cache handling (opens in a new tab).
Shopify
Versions Online Store 2.0 themes, Shopify admin, all plans, November 2026.
Shopify serves each published language under its own prefix (/de/, /en/) and exposes the request's language in request.locale. In layout/theme.liquid, the tag must be:
<html class="no-js" lang="{{ request.locale.iso_code }}">
Do the same in layout/password.liquid and in every other file of the layout/ folder. Languages are published in Settings > Languages. A translation app that translates in the browser without changing the URL does not solve the problem: the tag served remains that of the default language.
PrestaShop
Versions PrestaShop 8 and 9, Classic and Hummingbird themes.
The Classic and Hummingbird themes write the language of the displayed shop in their layout template (templates/layouts/layout-both-columns.tpl): <html lang="{$language.locale}">. Enable friendly URLs with a language prefix in Shop Parameters > Traffic & SEO, then check the language code of each language (de-de, fr-fr) in International > Localization > Languages. A third-party theme that writes a fixed value is fixed with the same variable.
Magento
Versions Magento Open Source and Adobe Commerce 2.4.
One store view per language, each with its own locale: Stores > Settings > Configuration > General > General > Locale Options, at store view level. The Luma theme then writes the language of the active view. Use store codes in the URL (Stores > Configuration > General > Web > Url Options > Add Store Code to Urls) or a domain per view, then flush the cache.
Drupal
Versions Drupal 10 and 11, core Language and Content Translation modules.
With the Language and Content Translation modules, Drupal writes the interface language for the current request in html.html.twig. Open Configuration > Regional and language > Languages > Detection and selection (/admin/config/regional/language/detection) and put the “URL” method first, with a prefix per language. Disable “Session” and “Browser” for the interface language: they would make lang vary from one visitor to another.
Laravel
Versions Laravel 11 to 13. The middleware is attached to the routes: nothing to register in bootstrap/app.php.
Put the language in the first URL segment and set the locale in a middleware. First declare the supported languages in config/app.php:
'supported_locales' => ['fr', 'en', 'de'],
Create app/Http/Middleware/SetLocaleFromUrl.php:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\URL;
use Symfony\Component\HttpFoundation\Response;
class SetLocaleFromUrl
{
public function handle(Request $request, Closure $next): Response
{
$locale = $request->route('locale');
if (! in_array($locale, config('app.supported_locales'), true)) {
abort(404);
}
App::setLocale($locale);
URL::defaults(['locale' => $locale]);
$request->route()->forgetParameter('locale');
return $next($request);
}
}
In routes/web.php:
use App\Http\Middleware\SetLocaleFromUrl;
Route::prefix('{locale}')
->where(['locale' => 'fr|en|de'])
->middleware(SetLocaleFromUrl::class)
->group(function () {
Route::get('/', [HomeController::class, 'index'])->name('home');
});
The layout template stays the same: <html lang="{{ str_replace('_', '-', app()->getLocale()) }}">. forgetParameter prevents the language from arriving as the first argument of every controller method. Do not read the language from the session in this middleware.
Symfony
Versions Symfony 6.4, 7 and 8.
The special {_locale} parameter sets the request's locale:
#[Route('/{_locale}/tarifs', name: 'pricing', requirements: ['_locale' => 'fr|en|de'])]
public function pricing(): Response
In templates/base.html.twig: <html lang="{{ app.request.locale|replace({'_': '-'}) }}">.
Next.js
Versions Next.js 15.5 and 16 (App Router and Pages Router).
With both routers, the language must be in the server-rendered HTML. Do not write document.documentElement.lang = … in a client component: the value would not be in the initial HTML.
App Router
The root layout goes under the language segment, app/[lang]/layout.tsx. The global LayoutProps type has existed since Next.js 15.5:
import { notFound } from 'next/navigation'
const locales = ['fr', 'en', 'de']
export async function generateStaticParams() {
return locales.map((lang) => ({ lang }))
}
export default async function RootLayout({ children, params }: LayoutProps<'/[lang]'>) {
const { lang } = await params
if (!locales.includes(lang)) {
notFound()
}
return (
<html lang={lang}>
<body>{children}</body>
</html>
)
}
Pages Router
The i18n configuration in next.config.js is enough: Next.js itself writes the route's locale into the lang attribute of <html>.
module.exports = {
i18n: {
locales: ['fr', 'en', 'de'],
defaultLocale: 'fr',
},
}
Do not write a fixed value in pages/_document.tsx (<Html lang="fr">): it would override the route's locale.
Nuxt
Versions Nuxt 3 and 4, @nuxtjs/i18n module 9 and 10.
With the Nuxt i18n module, declare the language of each locale and the prefix strategy in nuxt.config.ts:
export default defineNuxtConfig({
modules: ['@nuxtjs/i18n'],
i18n: {
strategy: 'prefix',
defaultLocale: 'fr',
locales: [
{ code: 'fr', language: 'fr' },
{ code: 'en', language: 'en' },
{ code: 'de', language: 'de' },
],
},
})
Then in app.vue (or the layout), apply to <html> the attributes computed by useLocaleHead() for the current route:
<script setup lang="ts">
const head = useLocaleHead()
useHead(() => ({
htmlAttrs: {
lang: head.value.htmlAttrs.lang,
dir: head.value.htmlAttrs.dir,
},
}))
</script>
Versions 8 and earlier of the module call the language field iso: follow the documentation for your version.
Astro
Versions Astro 5 to 7.
Declare the languages in astro.config.mjs (i18n: { locales: ['fr', 'en', 'de'], defaultLocale: 'fr', routing: { prefixDefaultLocale: true } }), put the pages in src/pages/fr/, src/pages/en/…, then in the layout: <html lang={Astro.currentLocale}>. Without prefixDefaultLocale: true, the default language's pages go at the root of src/pages/, with no fr/ folder.
Common mistakes
- Language read from a cookie or the session: the value changes from one visitor to another; a bot without cookies gets the default language on every version. See test without cookies (opens in a new tab).
- Language inferred from
Accept-Language: same problem, only worse, since Googlebot generally does not send this header. - Value set in JavaScript after loading: missing from the initial HTML, and therefore invisible to bots that do not run scripts.
- Cache shared between languages: a page cached with
lang="fr"served on the German URL when the cache key does not take the language into account. - Contradiction between
langandhreflang:lang="fr"on a page announced ashreflang="de". - Underscore:
lang="de_DE"copied from the system locale; BCP 47 uses a hyphen. - Forgotten pages: 404, search results, cart, pages generated by a plugin, still in the default language.
Frequently asked questions
How do you change the lang attribute according to the page's language?
Make the lang attribute depend on the requested URL: a /de/ prefix, a subdomain or a domain. The server resolves the language from the URL, then writes it into the html tag before sending the page. On WordPress, a multilingual plugin handles it; on Laravel, a middleware sets the locale; on Next.js, the root layout goes under the [lang] segment. Never rely on a cookie, the session or the browser language.
Must the lang attribute match the hreflang value?
Yes, the language part must be identical. If a page declares itself as hreflang="de-AT" in its annotations, its lang attribute is de or de-AT, never fr. Both use the same BCP 47 syntax with a hyphen. Lang describes the language of the text for the browser and assistive technologies; hreflang links equivalent versions for search engines. A contradiction between them usually points to a misconfigured template or cache.
Can you set the page language with JavaScript?
It is not recommended for the page's main language. A script that changes document.documentElement.lang after loading leaves the wrong value in the initial HTML, the one read by bots that do not run JavaScript and the one stored by caches. Write the attribute on the server or at static generation time. JavaScript only makes sense for applications rendered entirely on the client, and server-side rendering is still preferable there.
Should you add the Content-Language HTTP header?
It is not mandatory. The Content-Language header describes the intended audience of the response and can list several languages; the lang attribute of the html tag remains the reference for the language of the text. If you send it, align it with lang for each version, for example with a URL prefix mapping in Apache or Nginx. Avoid the meta http-equiv Content-Language tag, however, which the W3C advises against.
Resources
- W3C: Declaring language in HTMLw3.org
- W3C: HTTP headers, meta elements and language informationw3.org
- W3C: Understanding Success Criterion 3.1.1: Language of Pagew3.org
- Google Search Central: Managing multi-regional and multilingual sitesdevelopers.google.com
- MDN: lang attributedeveloper.mozilla.org
- Next.js: Internationalizationnextjs.org
- Nuxt i18n: useLocaleHeadi18n.nuxtjs.org
- Drupal: Multilingual guidedrupal.org
- Shopify: request Liquid objectshopify.dev
Updated on
Topic checklist (PDF)