In Drupal 7, I believe you could do this with Rules. The Rules module is technically available for Drupal 8, but I couldn't figure out how to use it, so I'll show you how to wire up a custom module that redirects manually based on whatever your criteria is.
The basic idea is, in order to do custom redirects, you have to register an EventSubscriber service, subscribe to REQUEST KernelEvent, and then you have access to the entire request object.
In my company's case, I wrote a custom module called "redirect", so that's what this example will use.
First, create a redirect.services.yml file.
services:
redirect.subscriber:
class: Drupal\redirect\EventSubscriber\RedirectSubscriber
tags:
- { name: event_subscriber}
Then, create the class referenced above (Drupal\redirect\EventSubscriber\RedirectSubscriber
) in src/EventSubscriber/RedirectSubscriber.php
.
<?php
namespace Drupal\redirect\EventSubscriber;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\node\Entity\Node;
class RedirectSubscriber implements EventSubscriberInterface {
public function redirect(GetResponseEvent $event) {
$request = $event->getRequest();
$baseUrl = $request->getBaseUrl();
$attr = $request->attributes;
$roles = \Drupal::currentUser()->getRoles();
if ($attr !== null) {
$node = $attr->get('node');
if ($node !== null && $node instanceof Node) {
$type = $node->get('type')->getString();
if ($type == 'seel_lesson_plan' && !in_array('administrator', $roles)) {
$event->setResponse(
new RedirectResponse("$baseUrl/url-to-404-page")
);
}
}
}
}
static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = ['redirect'];
return $events;
}
}
To get a better idea of how this works, read an explanation of registering event subscribers, the official Events API page, and this other Drupal SE question about redirecting content pages.