Rotate URLs with PHP Location Header Exit Code at Fifty Percent Random While Preserving URL string

June 13, 2018 Code, PHP, URL redirect

This is a great piece of code to rotate 2 separate landing page urls using PHP location headers and a 50% random string. This code also preserves the URL string so that any url string variables are sent to the rotated links of the outbound pages.

We achieve this by using a simple redirect script php header.

This snippet of code is excellent for the testing of different landing page offers with different designs and elements, so you may determine which page layout and design performs better.

First, I set up an index.php page in a directory on my site. In this case is was just a simple /r directory. So the file structure would look something like this

https://www.nickclaeboe.com/r/

and the php code would be added to the index.php file in this /r directory.

<?php
if (mt_rand(0,1) == 0) {
header("Location:https://www.nickclaeboe.com/blog/post1/?". $_SERVER['QUERY_STRING']);
exit;
} else {
header("Location:https://www.nickclaeboe.com/blog/post2/?". $_SERVER['QUERY_STRING']);
exit;
}
?>

Using this code, and with it preserving your url string, your traffic link would look something like:

https://www.nickclaeboe.com/r/?yourVariable=this

and with the script above installed on the index.php of the /r directory, the random string in the php snippet will send your traffic to each link approximately 50% of the time, evening out the traffic sent to the 2 pages you are testing. Ultimately, you will see your traffic sent to each page and those links will now look something like this:

https://www.nickclaeboe.com/blog/post1/?yourVariable=this

and

https://www.nickclaeboe.com/blog/post2/?yourVariable=this

I hope this helps you out as much as it’s helped me out.

It’s a very quick and easy way to test 2 separate landing pages with different landing page elements to test what page converts better based on your page variables.