This implementation of hook_init() should be present on your subdomains but not on your main domain:
function YOUR_MODULE_NAME_init() { if(!isset($_COOKIE['your_cookie_name'])) { /*Your need to set cookie for your main domain, as well as for all your subdomains otherwise once a user visits another subdomain by typing the url directly in the address bar the cookie would be overwritten*/ setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'example.com'); setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site1.example.com'); setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site2.example.com'); ... setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site5.example.com'); } else { header('Location: ' . base64_decode($_COOKIE['your_cookie_name'])); } }
Your main domain should have a module with the following code:
function YOUR_MODULE_NAME_init() { if(isset($_COOKIE['your_cookie_name'])) { header('Location: ' . base64_decode($_COOKIE['your_cookie_name'])); } }
I didn't test this code, but I am positive it should work, or at the very least it illustrates the approach.