drupal_set_message for anonymous user
The fact that you use header() and exit is most likely the problem.

You need to use response objects that you return to properly terminate the request and write the session data.

You can't do this anywhere, I'd recommend implement a Request event subscriber. \Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber is a simple example for this:

class RedirectLeadingSlashesSubscriber implements EventSubscriberInterface {

  public function redirect(GetResponseEvent $event) {
    $request = $event-&gt;getRequest();
    // Get the requested path minus the base path.
    $path = $request-&gt;getPathInfo();

    if (strpos($path, '//') === 0) {
      $path = '/' . ltrim($path, '/');
      $qs = $request-&gt;getQueryString();
      if ($qs) {
        $qs = '?' . $qs;
      }
      $event-&gt;setResponse(new CacheableRedirectResponse($request-&gt;getUriForPath($path) . $qs));
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['redirect', 1000];
    return $events;
  }

}


And then register that in yourmodule.services.yml:

redirect_leading_slashes_subscriber:
  class: Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber
  tags:
    - { name: event_subscriber }