【问题标题】:Infinite loop on Geo Redirect地理重定向上的无限循环
【发布时间】:2015-10-26 23:09:22
【问题描述】:

我有 3 个针对不同地区的网站,它们都有自己的位置特定内容:

我想根据访问者的 IP 地址将访问者重定向到相应的网站。例如,如果用户从德国登陆http://dev.logichub.net/demo/fr/,那么他/她必须被重定向到德国网站,即http://dev.logichub.net/demo/de/。我想在所有 3 个网站上实现相同的行为。

我在这3个网站的首页上放了如下代码:

// get visitor IP address and process
$geo_data = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR']) );

if ( ! empty( $geo_data ) ) {

    switch ( $geo_data['geoplugin_countryCode'] ) {

            // redirect French visitors to FR website
            case "FR":
                echo '<script>window.location.replace( "http://dev.logichub.net/demo/fr/" );</script>';
                break;

            // redirect German visitors to DE website
            case "DE":
                echo '<script>window.location.replace( "http://dev.logichub.net/demo/de/" );</script>';
                break;

            // redirect all others to international website
            default:
                echo '<script>window.location.replace( "http://dev.logichub.net/demo/" );</script>';
    }
}

除了重定向网站上的无限循环外,它的工作原理与我想要的完全一样。访问者被完美重定向,但新网站永远加载。如何停止无限循环,以便一旦访问者重定向到正确的网站,就不会再发生重定向?

【问题讨论】:

    标签: infinite-loop url-redirection geoip


    【解决方案1】:

    在尝试重定向之前,您必须检查用户是否在正确的域中。这是一个完全用 PHP 制作的解决方案:

    <?php
    session_start();
    
    $currentUrl = explode('/', "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
    $currentCountry = isset($currentUrl[4]) ? $currentUrl[4] : '';
    
    if(empty($_SESSION['country'])) {
        $geo_data = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR']) );
    
        if(!empty($geo_data)) {
            $country = $geo_data['geoplugin_countryCode'];
            $_SESSION['country'] = $country = ($country != 'FR' || $country != 'DE') ? '' : $country;
        }
    }
    
    if($currentCountry != $_SESSION['country'])
        header('Location: http://dev.logichub.net/demo/'.$country);
    

    您可以通过获取当前国家/地区而不在 URL 中搜索它来改进此代码(例如,通过在文件中定义它),但实际上,它应该会更好。

    【讨论】:

    • 感谢您的帮助。会议在这里的目的是什么?这是 3 个不同的独立网站。忘记包括我正在使用 WordPress 在当前活动主题的 functions.php 中添加此代码的事实。
    • 它阻止你继续使用API​​,将保存最终用户,与webServices相关的请求时间
    猜你喜欢
    • 2020-09-22
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2013-01-25
    • 2012-06-08
    • 2019-08-31
    相关资源
    最近更新 更多