Last active
October 18, 2023 08:53
-
-
Save 867/7179e71b664502c7c1e511ecb5f7d678 to your computer and use it in GitHub Desktop.
個人ブログ用:海外からのアクセスをグローバルサイトにリダイレクトする(MAXMINDのGeoIP2使用)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 海外からのアクセスをグローバルサイトにリダイレクトする(MAXMINDのGeoIP2使用) | |
* | |
*/ | |
<script src="//geoip-js.com/js/apis/geoip2/v2.1/geoip2.js"></script> | |
<script> | |
const onSuccess = function(response) { | |
if ((response.country.iso_code !== 'JP') && (response.country.iso_code !== 'JA')) { | |
fetch('//raw.githubusercontent.com/monperrus/crawler-user-agents/master/crawler-user-agents.json') | |
.then(function(response) { | |
return response.json(); | |
}) | |
.then(function(data) { | |
const patterns = data.map(function(ua) { | |
return ua.pattern; | |
}); | |
const isCrawler = new RegExp('(' + patterns.join('|') + ')').test(navigator.userAgent); | |
if (!isCrawler) { | |
// Redirect to Global site | |
window.location = 'https://www.example.com'; | |
} | |
}); | |
} | |
}; | |
const onError = function(error) { | |
console.log('GEOIP cannot get IP location, ', error); | |
}; | |
if (geoip2) { | |
geoip2.country(onSuccess, onError); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment