skip to Main Content

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


  1. Chosen as BEST ANSWER

    Finally found a solution using

    $country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];
    

  2. Make sure you generated no output before you call header().
    Check for whitespace / invisible characters before <?php. Check that also in IP2Location.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:

    if($record == 'US') {
        header('Location: https://mywebsite.com/en');
        exit;
    }
    

    see https://www.php.net/manual/en/function.header.php
    it says it will use 302 instead of your 301:

    The second special case is the "Location:" header. Not only does it
    send this header back to the browser, but it also returns a REDIRECT
    (302) status code to the browser unless the 201 or a 3xx status code
    has already been set.

    <?php
    header("Location: http://www.example.com/"); /* Redirect browser */
    
    /* Make sure that code below does not get executed when we redirect. */
    exit;
    ?>
    
    Login or Signup to reply.
  3. HTTP 301 redirect should be set as third parameter to header() function

    <?php
    
    error_reporting(E_ALL);
    ini_set("display_errors", 1);
    
    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('Location: https://mywebsite.com/en', true, 301);
        exit;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search