javascript - 如果浏览器语言不是俄语,则重定向到英文版本
问题描述
我想使用 php 或 js 重定向没有俄罗斯浏览器的用户。
我的代码看起来像这样但不起作用:
<?php
$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
if ($locale != "ru_RU"){
header('Location: https://www.site/en/');
die();
}
?>
如果我写echo $locale
它ru_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>
功能不应影响页面的加载速度。你知道怎么做吗?
解决方案
使用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;
}
推荐阅读
- javascript - 计算并返回 2 个数组中每个位置的距离
- python - 是否有可能在 phython 中使用更大的列表?
- android - RecyclerView 滑动删除 防止在不可删除项目上删除动画
- c# - LeftControl 的 Selenium C# KeyDown 和 KeyUp 在 IE11 中不起作用
- c - 在枚举中使用实例化
- php - 基于 mySQL 表名填充的下拉列表,并添加了按钮
- r - 如何使用 OpenSearch 从 R 中搜索 Internet 以查找包含指定术语的页面并将结果存储在数据表中
- php - 如何在使用PHPEXCEL插入时从数据库中的excel文件中插入日期时间(2019-03-01 24:30:15)
- bots - 如何让机器人识别何时提到角色,然后做出回应?
- javascript - 如何在javascript中更改函数中传递的变量的值?