This script uses a settings object to easily adjust the default language, fallback language, and list of supported languages, then checks if the user is on the root path and hasn’t been redirected yet; it retrieves the browser’s two-letter language code and, if it matches a supported language, redirects the user accordingly, otherwise it falls back to a designated language all while ensuring redirection happens only once via localStorage check.
This saves you from checking the ip and location or region and paying api… No need to do that this just checks the browser language and forwards the user to correct /en /es /xx site lang depending on the browser language. Easiest way to create language/location/regional auto forward for multi language websites 😎
(function() { // Settings for language redirection var settings = { defaultLang: 'de', // Default "/" root site language (no redirection) fallbackLang: 'en', // Fallback language if user's language is not supported supportedLangs: ['fr', 'it', 'es'] // Supported language codes with dedicated paths }; // Exit if already redirected or not at the root path. if (localStorage.getItem('langRedirectDone') || window.location.pathname !== '/') { return; } // Get and normalize the user's browser language to a two-letter code. var userLang = (navigator.language || navigator.userLanguage).toLowerCase().substring(0, 2); // Redirect based on the user's language: no redirect if default, specific path if supported, or fallback otherwise. if (userLang === settings.defaultLang) { return; } else if (settings.supportedLangs.indexOf(userLang) !== -1) { localStorage.setItem('langRedirectDone', 'true'); window.location.replace('/' + userLang); } else { localStorage.setItem('langRedirectDone', 'true'); window.location.replace('/' + settings.fallbackLang); } })();