If you want to do A/B split testing with nginx, you usually are directed to the split clients module.

However, most of us don’t have this module compiled into their nginx installations and this usually results in using our code to do the actual A/B spliting.

Here is how you can do that, without the addition of other modules.

First you need to create a map that will hold your two URLs:

map $time_local $split_redirect {
# 27/Jul/2017:02:33:06 -0500
    "~[13579] \-.*$" @location1;
    "~[02468] \-.*$" @location2;

As you can see, I’m using the $time_local variable for the split. Everyone that access the site on even seconds will go to @location1 and the others to @location2. That is all the “magic” that you would need :)

Then you have two options :) First is to use if, but we know if is evil, so the second option is to use internal error redirects :)

    location ~ ^/page {
        recursive_error_pages on;
        error_page 412 = $split_redirect;
        return 412;
    }   

    location @location1 {
        internal;
        return 301 http://site/page1.html;
    }   

    location @location2 {
        internal;
        return 301 http://site/page2.html;
    }

if you decide to go the if route, here is how you should do it.

You need to change the map to have your locations:

map $time_local $split_redirect {
# 27/Jul/2017:02:33:06 -0500
    "~[13579] \-.*$" http://site/page1.html;;
    "~[02468] \-.*$" http://site/page2.html;;

and then simply add this if to your config:

    if ($split_redirect) {
        rewrite ^ $split_redirect permanent;
    }

Comments are closed.

Posted by HackMan
Dated: 27th July 2017
Filled Under: Uncategorized