Reputation: 11
I want to redirect the visitors from Australian IP to a particular domain landing page. If the visitor of Australian IP hit a domain server URL from any browser address bar, then the URL change & redirect to the same domain another location folder. I want to implement this requirement with a JavaScript or jQuery code for the normal HTML page. (Not any dynamic page)
For example, my website is "www.example.com" & I want to redirect all the Australian countries IP to "www.example.com/aus", But I don't want to share my location when hit the URL into browser address bar, which came up when we going to implement with geolocation tracking with a location share alert box. Can anyone help me or reconstruct a script to make it work for its purpose? Thanks a lot in advance.
Upvotes: 0
Views: 1553
Reputation: 477
Get the country code by using ipgeolocation.io API, then redirect the Australian visitors to www.example.com/aus. The following code will help you a lot.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (4 === this.readyState && 200 === this.status) {
var json = JSON.parse(this.responseText);
if (json.country_code2 == "AU" && window.location.hostname !== "http://www.example.com/aus") {
window.location.href = "http://www.example.com/aus";
}else {
window.location.href = "https://www.exmaple.com";
}
}
}
request.open("GET", "https ://api.ipgeolocation.io/ipgeo?apiKey=YOUR_API_KEY&fields=country_code2", false);
request.setRequestHeader("Accept", "application/json");
request.send();
Upvotes: 2
Reputation: 22321
You can get Country code using ipinfo.io
and compare with end user country if match further your process.
$.get("https://ipinfo.io", function(response) {
var Coutntry_Code = response.country;
var url = window.location.href;
//var country = url.split(/[\s/]+/); // You Get country code from url
var country = 'us' // Set value for test. Comment this line and uncomment above line in your project.
if (Coutntry_Code === country) {
alert('Your url to redirect');
} else {
alert('Your another url to redirect or block page');
}
}, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 0