0

I have my WordPress site hosted on nginx server. Now, I have created a sub-domain name say us.example.com How can I change the WordPress URL according to country wise when the site is open in united states i.e us.example.com?

Theo Orphanos
  • 1,417
  • 1
  • 19
  • 27

1 Answers1

0

There is a website that provides geolocation of a given ip (actually there are many, but I will just focus on this one): http://ip-api.com/

You can use the information they provide in order to redirect your visitors to the appropriate sub-domain like this:

$this_ip = $_SERVER["REMOTE_ADDR"];
$get_ip_info = file_get_contents("http://ip-api.com/json/".$this_ip);
$ip_info = json_decode($get_ip_info);
$countryCode = strtolower($ip_info->{"countryCode"});

header("Location: http://".$countryCode.".example.com");    

Of course, there are numerous countries and since is not practically possible to maintain a subdomain for each one, you can use the "if" statement to narrow down the redirect options:

if($countryCode=="fr"){ //french
    header("Location: http://fr.example.com");
}else
if($countryCode=="de"){ //german
    header("Location: http://de.example.com");
}else
if($countryCode=="gr"){ //greek
    header("Location: http://gr.example.com");
}else{ //universal
    header("Location: http://www.example.com");
}

Hope this helps you!

Theo Orphanos
  • 1,417
  • 1
  • 19
  • 27
  • Its not working.the site is not opening when we redirect it to sub domain.. actually – Heena Gulati Apr 10 '17 at 10:50
  • If you go directly to (for example) de.example.com the site works, but if you go there using my script is not working?? Is that what you mean? – Theo Orphanos Apr 10 '17 at 10:55
  • First try to "echo" the variable "countryCode". Then make sure that the sub-domain which corresponds to that value exists in your project... – Theo Orphanos Apr 10 '17 at 11:00
  • I have a wordpress website with example.com domain and in database the siteurl is example.com. and i have created a subdomain i.e us.example.com, No wordpress installation in the sub-domain. Now, i want when i open us.example.com ,the site will open whose in this domain example.com but the domain name shows us.example.com. I hope you understand what i am asking. I am getting stuck please help me out – Heena Gulati Apr 11 '17 at 06:33
  • In this case, you need to rewrite the url according to subdomain, and redirect to your main domain. This looks like an nginx issue and I suggest you read this: http://stackoverflow.com/questions/33443290/nginx-rewrite-any-sub-domain-to-specific-url (or this: http://stackoverflow.com/questions/15266253/nginx-rewrite-all-wildcard-subdomains-to-www-site-com) – Theo Orphanos Apr 11 '17 at 08:20