【问题标题】:WordPress: Using CloudFlare to redirect to URL based on Country IPWordPress:使用 CloudFlare 根据国家 IP 重定向到 URL
【发布时间】:2018-10-27 01:44:02
【问题描述】:

我在我的客户 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

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

【问题讨论】:

  • 嗯。 PHP 代码试图重定向每个人,这几乎肯定不是您想要的。我不确定.htaccess。乍一看还可以,但十年前我抛弃了 Apache(出于不相关的原因)...

标签: php wordpress redirect url-redirection ipv6


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    使用 wp_redirect() 函数和 template_redirect 钩子https://developer.wordpress.org/reference/functions/wp_redirect/

    【讨论】:

    • 所以应该是这样的函数 redirect () { If ("your conditions") { $url = 'my_url'; wp_redirect ($url);出口; }} add_action('template_redirect', 'redirect');
    • 我试过了,但我不认为重定向正在发生。我知道我必须包含 $country_code = $_SERVER ["HTTP_CF_IPCOUNTRY"];在混合中,我认为应该在函数内部,对吧?
    猜你喜欢
    • 2012-04-07
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多