How to redirect a user to a visited sub-domain on his next visit to main domain I have a website say example.com with 5 sub-domains: site1.example.com, site2.example.com, site3.example.com, site4.example.com, and site5.example.com.

When users visit example.com, they are presented with the other 5 sub-domains to choose from. I want to implement something that redirect the users to the sub-domain they choose the first time they visit the main domain. I know I can use cookies for this, but how can I implement this in Drupal?
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.