Doing this with mod_geoip2
on the server with a local geolocation database is definitely the best approach here, but if your not able to do that for whatever reason then an alternative is to use an API like http://ipinfo.io. It returns lots of details for a given IP:
$ curl ipinfo.io
{
"ip": "208.54.39.191",
"hostname": "mbf2736d0.tmodns.net",
"city": "Los Angeles",
"region": "California",
"country": "US",
"loc": "34.0522,-118.2437",
"org": "AS21928 T-Mobile USA, Inc.",
"postal": "90013"
}
You just need the country though, so you can speed things up a tiny bit by requesting just that:
$ curl ipinfo.io/country
US
Then you can request this information for the current user and redirect them to a different URL if they're not on the correct one. Here's what the javascript code to do that would look like:
$.get('http://ipinfo.io/country', function(country) {
var country_is_no = country.trim() == 'NO';
if(country_is_no and document.location.pathname != '/no') {
document.location = '/no';
}
if(!country_is_no && document.location.pathname != '/en') {
document.location = '/en';
}
}, "jsonp");
That only allows you to have 2 pages though (/no, and /en). That might be fine for your purposes, but an alternative would be to have no and en subdomains, and keep the rest of the content in the same place, just like wikipedia:
If you were to setup the 2 subdomains then you could extract that with the following javascript, and then redirect based on that:
var subdomain = document.location.hostname.split('.')[0];