如何按特定顺序重定向我的网页? [关闭]

I'm looking for a way to redirect my webpage to two URLs in order, this could be in PHP but if you got any other ideas please hit me up! It should work like this:

Visitor 1 -> redirect to site1.com
visitor 2 -> redirect to site2.com
visitor 3 -> redirect to site1.com
visitor 4 -> redirect to site2.com

I think you get the idea :)

The main issue with this is you need info about the previous visitor.

For this, you need to keep track of what each visitor is redirected to, so the next one will have access to the info.

If you have only one webserver, this is easy. Just create an empty file for odds visits, and delete it for even visits.

 // Untested code, just to give the general idea

$trackingFile='/usr/share/whatever/oddvisit';
if(file_exists($trackingFile)){
    // even visitor
    unlink($trackingFile);
    Header('Location: http://url2.com');
    exit;
}else{
    // odd visitor
    touch($trackingFile);
    Header('Location: http://url1.com');
    exit;
}

If you have multiple webservers, this is a little bit trickier.

If you have no NFS all your webservers can access, you can store the odd/even info in a database. But it's best if you don't have a huge amount of trafic.

If you have a lot trafic, I think the best solution would be to accept that each webservers will redirect visitors they get, independantly of what other webservers do. With very large numbers, you should get a pretty decent 50/50 redirections.

You need what's called 'round robin'.

In each visitor redirect based on a current position. This is subject to a race condition, but it probably doesn't matter for the purpose:

// Suggested location for RR counter
define('ROUND_ROBIN_FILE', '/tmp/site-counter.txt');

// Here's your queue
$possibleRedirects = array('site1.com', 'site2.com', 'site3.com');

// Get the current position
$position = file_get_contents(ROUND_ROBIN_FILE);
if (empty($position)) {
     $position = 0;
}
$position = ($position + 1) % count($possibleRedirects);

// Save the current position
file_put_contents($position, ROUND_ROBIN_FILE);

What I mean by 'round robin' is that you have a queue system where you store all available redirect URLs. When user 1 visits the page you remove last redirect URL from the queue/stack and redirect user. Save this action in a database either entire URL or the way @halfer suggested.

Then user 2 visits and you check if your queue is empty, if it is not empty then remove another URL from the queue and redirect user 2 and save in database. If queue is empty reset the queue to all available redirects and reset the database.