Skip to content

Instantly share code, notes, and snippets.

@birender
Forked from iconifyit/htaccess-ab-test
Created July 17, 2019 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save birender/db0f07c99ad82c8045ead9a83320b720 to your computer and use it in GitHub Desktop.
Save birender/db0f07c99ad82c8045ead9a83320b720 to your computer and use it in GitHub Desktop.
A/B Testing with htaccess
# ############################### #
# A/B TESTING (START) #
# ############################### #
# (1) Check if our cookie is already set.
# If so, redirect to the previously-viewed page.
RewriteCond %{HTTP_COOKIE} ab_test_vers=([^;]+)
RewriteRule ^tracking$ https://yourdomain.com/test-page/%1 [cookie=ab_test_vers:true:yourdomain.com,L]
# (2) If no cookie is set (new visitor)
# AND the current time is on an even-numbered second
# Rewrite to /test-option-a AND set our cookie
RewriteCond %{HTTP_COOKIE} !ab_test_vers=([^;]+)
RewriteCond %{TIME_SEC} [02468]$
RewriteRule ^test-page$ /test-option-a [cookie=ab_test_vers:even:yourdomain.com,L]
# (3) If no cookie is set (new visitor)
# AND the current time is on an odd-numbered second
# Rewrite to /test-option-a AND set our cookie
RewriteCond %{HTTP_COOKIE} !ab_test_vers=([^;]+)
RewriteCond %{TIME_SEC} [13579]$
RewriteRule ^test-page$ /test-option-b [cookie=ab_test_vers:odd:yourdomain.com,L]
# (4) We can use the rewritten URL to redirect the vistor to the page
# they should see. The redirect can be to your won domain OR to an
# external domain.
Redirect 302 /test-option-a https://yourdomain.com/actual-test-page-a
Redirect 302 /test-option-b https://yourdomain.com/actual-test-page-b
# NOTE: You can track the test results using Google Analytics by tracking the
# landing pages and referrers.
# ############################### #
# A/B TESTING (END) #
# ############################### #
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment