我购买了 Maxmind GeoIP2 一段时间,我想根据国家/地区进行简单的重定向,但即使在他们的网站上,似乎也没有明确的答案如何做到这一点。我不擅长编码,但我正在尝试了解它是如何工作的......
例如,我的网站是 google.com,我想将某些国家/地区重定向到 yahoo.com,我想出了此代码,但它会将每个人重定向到 yahoo.com。任何人都可以帮助我或重建这个脚本以使其达到其目的吗?非常感谢..
<script src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>
<script language="JavaScript">
var user_country = geoip2.country(
function (response) {
if (response.country.iso_code === "FR"){window.location = "http://yahoo.com"}
else {window.location = "http://google.com"}
if (response.country.iso_code === "BE"){window.location = "http://yahoo.com"}
else {window.location = "http://google.com"}
if (response.country.iso_code === "PH"){window.location = "http://yahoo.com"}
else {window.location = "http://google.com"}
},
function (error) {
// handle error
}
);
</script>
最佳答案
我基于这个 Maxmind Tutorial 创建了一个更复杂的版本。您需要register your domain at Maxmind and purchase credits使用 GeoIP2 JavaScript 客户端 API(上述解决方案也是如此!)。玩得开心!
<script src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>
<script language="JavaScript">
var redirect = (function () {
/* Get actual URL */
var url = window.location.href;
/* This implements the actual redirection. */
var redirectBrowser = function (site) {
var uri = "https://www.example.com/" + site;
window.location = uri;
};
/* These are the country codes for the countries we have sites for.
* We will check to see if a visitor is coming from one of these countries.
* If they are, we redirect them to the country-specific site. If not, we
* redirect them to https://www.example.com/ */
var sites = {
"us": {"active": true, "target": "en-us"},
"gb": {"active": true, "target": "en-gb"},
"de": {"active": true, "target": "de"},
"fr": {"active": true, "target": "fr"},
"fi": {"active": true, "target": "fi"},
"hu": {"active": true, "target": "hu"},
"nl": {"active": true, "target": "nl"},
"se": {"active": true, "target": "sv"}
};
var defaultSite = "";
var onSuccess = function (geoipResponse) {
/* There's no guarantee that a successful response object
* has any particular property, so we need to code defensively. */
if (!geoipResponse.country.iso_code) {
redirectBrowser(defaultSite);
return;
}
/* ISO country codes are in upper case. */
var code = geoipResponse.country.iso_code.toLowerCase();
if ( sites[code].active ) {
redirectBrowser(sites[code].target);
}
else if ( url == defaultSite ) {
return;
}
else {
redirectBrowser(defaultSite);
}
};
/* We don't really care what the error is, we'll send them
* to the default site. */
var onError = function (error) {
redirectBrowser(defaultSite);
};
return function () {
geoip2.country( onSuccess, onError );
};
}());
redirect();
</script>
关于javascript - 如何使用 Maxmind Geoip2 Javascript 根据国家/地区重定向流量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27677612/