Redirecting different locations to different URL’s
-
I am trying to use WPengines GeoTarget to send visitors to the respective language versions of my website.
I’ve tried several code examples, including the one provided by WPengine themselves but all the ones I’ve tried end up in a redirect loop as many others people have found. I settled on this one as it seemed to be the most comprehensive and the only one I could get working.
I managed to get a single language version working for our UK site:
/** GEOIP REDIRECT but allow bots **/ function country_geo_redirect() { $country = getenv('HTTP_GEOIP_COUNTRY_CODE'); $agent = $_SERVER['HTTP_USER_AGENT']; $host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; if ( $host == 'example.com/en-gb/' || isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT']) || $country != "GB" ) { return; } wp_redirect('https://example.com/en-gb/', 301); exit; } add_action('init', 'country_geo_redirect');
However, when I finally got the syntax right for the elseif statements, the UK version doesn’t redirect anywhere anymore, and neither do any of the others:
function country_geo_redirect() { $country = getenv('HTTP_GEOIP_COUNTRY_CODE'); $agent = $_SERVER['HTTP_USER_AGENT']; $host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; if ( $host == 'example.com/en-gb/' || isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT']) || $country != "GB" ) { wp_redirect('https://example.com/en-gb/', 301); exit; } elseif ( $host == 'example.com/zh-hans/' || isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT']) || $country != "CN" ) { wp_redirect('https://example.com/zh-hans/', 301); exit; } elseif ( $host == 'example.com/ja/' || isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT']) || $country != "JP" ) { wp_redirect('https://example.com/ja/', 301); exit; } } add_action('init', 'country_geo_redirect');
Any idea where I’m going on here? This has been driving me nuts!
- The topic ‘Redirecting different locations to different URL’s’ is closed to new replies.