hook_entity_view_alter - redirect First up I'm very new to the Drupal way of things but have jumped on board with Drupal 8 and quite excited about the possibilities.

What I'm trying to do is redirect the default node view route (i.e. /node/12345/), for a specific content type, to a route I've setup in my module i.e. /module_name/view/12345/

Currently I've done this via a hook which I'm 99.9% is the wrong way to do it but it does work. However I'm getting warnings in my log file as other Drupal commands (including drush) occasionally trigger the hook.

Here is my code so far:

function gst_return_entity_view_alter(array &amp;$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
    if($entity-&gt;bundle() == 'gst_return') {
        header('Location: /gst_return/view/' . $entity-&gt;id());
        exit;
    }
}


Two questions really:


Is there a better way to be doing this? I'm sure there is.
If the above is acceptable then what can I add to it so that the header redirect (which probably should be a Drupal core redirect?) so that it is only triggered in the context of someone viewing the site.


Thanks for any assistance.
Instead of using header redirect try using RedirectResponse class which comes together with the Symfony HttpFoundation.

use Symfony\Component\HttpFoundation\RedirectResponse;

 function my_menu_callback_foo() {
    //....
    return new RedirectResponse(\Drupal::url('user.page'));
 }


Refer link for more details.