Disable reaching a node by its internal path I want a node to be reached only by its alias but not its internal path. The reason behind this is that I will create a node type, allow anon users to create such nodes, but the alias will contain a random text, so that only the user with the actual url information can revisit this page. Example:
www.example.com/node/9 -> only accessible by admin
www.example.com/34h356hrgc35yh4geg -> only accessible to anon users with this information.

If an anon user tries www.example.com/node/9, they should see Forbidden error or Not Found.
You can do this if speed is important in a middleware, checking if the request has no session and then block right away or in a request event subscriber after authentication checking for the path. Or a bit slower after routing if you want to include if the route matched is the canonical node route and use the node entity in your logic.

The easist but slowest is in a page preprocess hook. You can even do this in a theme. The cached page is varied by path and user permission by default and so the not found exception:

function mytheme_preprocess_page(&amp;$variables) {
  if (\Drupal::currentUser()-&gt;isAnonymous()) {
    if (isset($variables['node'])) {
      $node = $variables['node'];
      if ($node instanceof \Drupal\node\NodeInterface) {
        if ($node-&gt;getType() == 'article') {
          $path = \Drupal::request()-&gt;getRequestUri();
          if (preg_match('#/node/\d+/*$#', $path)) {
            throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
          }
        }
      }
    }
  }
}


Because the 404 response is cached by the page cache the performance should be OK for most cases.