So I do have a website hosted on my own server (UpCloud), using Plesk. I’m also using Cloudflare.
Basically I did create multiple directories for my website for different regions of the world(en/fr/de/etc…)
I do have a script like this in my index.php to automatically redirect the people based on their country.
<?php
require 'IP2Location.php';
$loc = new IP2Location('databases/IP-COUNTRY.BIN', IP2Location::FILE_IO);
$record = $loc->lookup($_SERVER['REMOTE_ADDR'], IP2Location::ALL);
if($record == 'US') {
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://mywebsite.com/en');
exit;
}
?>
The problem is that I’m getting this error, the 500. No mater what I’ve tried, it didn’t work. Adding some .httaccess code, adding some code I’ve found on internet for the Apache & nginx Settings, etc…
Did some of you had the same problem and solved it?
Thank you in advance!
EDIT: Found a working solution using
$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];
3
Answers
Finally found a solution using
Make sure you generated no output before you call
header()
.Check for whitespace / invisible characters before
<?php
. Check that also inIP2Location.php
.Not sure if this is related, but but you could try using only the "Location" header, not the first line of the HTTP response:
see https://www.php.net/manual/en/function.header.php
it says it will use 302 instead of your 301:
HTTP 301 redirect should be set as third parameter to
header()
function