php - WordPress:使用 CloudFlare 根据国家 IP 重定向到 URL
问题描述
我在我的客户 WordPress 网站上运行了 CloudFlare。在 CloudFlare 中,我启用了 IP 地理定位以及 IPv6 兼容性和 Psuedo IPv4。
我想要做的是让来自加拿大 IP 地址的任何人重定向到我的网站的加拿大版本。我在我的子主题的 header.php 中尝试了这段代码:
$country_code = $_SERVER ["HTTP_CF_IPCOUNTRY"];
if ($country_code=="CA") {
$link = 'https://ca.example.com';
}
else {
$link = 'https://example.com';
}
header("location:$link");
exit;
但这确实在美国方面造成了重定向错误。它似乎确实在加拿大正确重定向。那么我怎样才能让它在加拿大人获得重定向但其他人没有的地方工作呢?
我也在.htaccess中试过这个:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
SetEnvIf CF-IPCountry "(.*)$" Country=$1
RewriteCond %(ENV:Country) CA
RewriteRule ^(.*)$ https://ca.example.com/$1 [R,L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
现在这并没有导致任何错误,但它也没有重定向。
解决方案
将其粘贴到您的子主题的 functions.php 文件中。为我工作。
add_filter( 'after_setup_theme', 'ip_redirect_on_cloudflare', 1);
function ip_redirect_on_cloudflare()
{
$CFCountry = $_SERVER['HTTP_CF_IPCOUNTRY'];
switch ($CFCountry){
case "CA":
wp_redirect( 'https://ca.example.com' );
exit;
}
}
推荐阅读
- java - Spring批量导入期间枚举到字符串的转换失败
- html - 如何使用特定版本的 amphtml?
- angularjs - 如何在 AngularJs 中获取返回值?
- python - 我想创建一个程序,使用 python 使用基础知识按字母顺序查找最长的子字符串
- video - FFmpeg 视频过滤器损坏 mp4 文件
- google-analytics - Tableau Server 每小时谷歌分析更新
- mysql - 从 sql 语句中获取特定列
- c# - 创建安装文件后无法加载 DLL 'sqlite.interop.dll'
- ibm-watson - 无法授权 Watson 助手音频客户端
- flask - 两个flask Apps同域IIS