首页 > 解决方案 > 如果浏览器语言不是俄语,则重定向到英文版本

问题描述

我想使用 php 或 js 重定向没有俄罗斯浏览器的用户。

我的代码看起来像这样但不起作用:

<?php
$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
if ($locale != "ru_RU"){
header('Location: https://www.site/en/');
die();
}
?>

如果我写echo $localeru_RU只会在我登录管理面板的浏览器中写入(在普通浏览器中它不会显示任何内容)。我怎样才能让它在全球范围内运作?

我在 JS 中也有这个功能,但我不知道在这之后要写什么:

<script>
let uri = window.location;
let lang = window.navigator.language;
if( uri.href.indexOf('lang') < 0) {
    if (lang != 'ru-RU'){
    /*redirect to "/en/"      */
}
}
</script>

功能不应影响页面的加载速度。你知道怎么做吗?

标签: javascriptphpwordpressurlredirect

解决方案


使用Navigator 语言属性获取用户的浏览器语言,如果不是“ru-RU”,则使用Window Location Pathname获取当前页面路径并重定向到您的域 + /en + 页面路径。

// Get browser language
var navLang = navigator.language || navigator.userLanguage; 
// Check if it is Russian
if (navLang != 'ru-RU'){
    // Get the page path
    var path = window.location.pathname;
    // Redirect to an English page with the full path
    window.location.href = "/en" + path;
}

推荐阅读