Craft CMS: How to persist logins in Redis between redeploys

How to persist login sessions between redeploying Craft CMS and thus prevent users from being logged out. I couldn’t find a guide on how to do this for Craft CMS so when I finally figured it out I decided to share it here.

This has been tested with Craft CMS 2.6 and PHP 7.0.x on Heroku with the Heroku Redis addon. The following instructions expect that a Redis connection string is available as an environment variable called REDIS_URL. You’ll also need to add ext-redis to your composer.json file. Finally, you’ll need to update two files.

In your public/index.php (see the source of our starter setup):

<?php

// ommited code

// If a REDIS_URL connection string is available in the environment 
// we specify redis as a save_handler.
if(!empty($_ENV['REDIS_URL'])) {
  ini_set('session.save_handler','redis');
}

// ommited code

In your craft/config/general.php (see the source of our starter setup):

<?php

$prodRedisUrl = '';
if(!empty($_ENV['REDIS_URL'])) {
  $redisUrlParts = parse_url($_ENV['REDIS_URL']);
  $prodRedisUrl = "tcp://$redisUrlParts[host]:$redisUrlParts[port]?auth=$redisUrlParts[pass]";
}

// omitted code

return array(
  '*' => array(
    // omitted code
  ),
  'yourdeploydomain.com' => array(
      
    // omitted code

    /*
      Must be set since Craft uses this to fingerprint its 
      data caching and sessions
    */
    'appId' => 'anUniqueAppId', 
    
    'overridePhpSessionLocation' => $prodRedisUrl, 

    /* 
    From the Craft CMS docs: 
    "This should be set on load-balanced environments, 
    or servers where the craft/storage/runtime folder is 
    purged on a regular basis" 
    */
    'validationKey' => $_ENV['CRAFT_VALIDATION_KEY']
  )
)

After adding this code you should be good to go. Ping me on twitter if/when it works out, if you have any questions or if you encounter any issues with this how-to.

Best of luck! :)

Further reading: