javascripturlgeolocationserver-side-includes

Redirect certain urls based on location


I have a number of links to Amazon UK on my (Joomla 3.4) website - these are links to buy books. They are basically 'Buy Now' buttons that take the user to the relevant Amazon UK item page (e.g www.amazon.co.uk/myBook) - html code below

<a class="btn btn-primary" href="http://www.amazon.co.uk/myBook...">Buy</a>

What I would like to do is re-direct US visitors to www.amazon.com

<a class="btn btn-primary" href="http://www.amazon.com/myBook...">Buy</a>

I know I could just add another button ('Buy US') but I only want one button per page.

I though I could perhaps either modify the .htaccess file, or add some javascript code so that vititors from the us will be taken to .com and not .co.uk?

I was looking at the geoPlugin and IP2Location - can either or these be used to achieve this?

Perhaps I could modify the IP2Location code (below) somehow?

<?php
require_once '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: http://amazon.com');
    exit;
}
?>

Not sure how I can user server side includes to achievce this?

Any help or direction is appreciated, I'm keen to learn by myself.


Solution

  • You can edit /index.php in Joomla to as below:

    $output = ob_get_clean();
    
    require_once JPATH_LIBRARIES . '/IP2Location.php';
    
    $db = new \IP2Location\Database('./databases/IP-COUNTRY-SAMPLE.BIN');
    $records = $db->lookup($_SERVER['REMOTE_ADDR']);
    
    if($records['countryCode'] == 'US'){
          echo str_replace('www.amazon.co.uk', 'www.amazon.com', $output);
    }
    else{
          echo $output;
    }