首页 > 解决方案 > 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

现在这并没有导致任何错误,但它也没有重定向。

标签: phpwordpressredirecturl-redirectionipv6

解决方案


将其粘贴到您的子主题的 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;
    }
}

推荐阅读