Skip to content

Instantly share code, notes, and snippets.

@867
Last active October 18, 2023 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 867/7179e71b664502c7c1e511ecb5f7d678 to your computer and use it in GitHub Desktop.
Save 867/7179e71b664502c7c1e511ecb5f7d678 to your computer and use it in GitHub Desktop.
個人ブログ用:海外からのアクセスをグローバルサイトにリダイレクトする(MAXMINDのGeoIP2使用)
/**
* 海外からのアクセスをグローバルサイトにリダイレクトする(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