hook_node_view_alter(&$vars, $hook) {

  global $base_url;

  if($vars['#node']->status == 0) {
    header('Location: '.$base_url.'/?errCode');

Simple hook to redirect unpublished nodes to prevent 404s (this is just a proof of concept).

Factor 1: There is already existing unpublished pages that have redirects (via the Redirect Module from Drupal Core) - this shouldn't affect that.

This is placed in my theme/template.php file but I'm not confident that this hook is best suited (although it works). Is there a lower level menu router hook which I can use?

1 Answer 1


Is there a lower level menu router hook which I can use?

Yes, there is - you would need to use hook_menu_alter() to achieve this. Here's the code you should use:

function YOUR_MODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'YOUR_MODULE_node_page_handler';

function YOUR_MODULE_node_page_handler($node) {
  // If the node is unpublished, redirect the user.
  // Note: I would recommend adding an extra check so administrators and
  // users who can manage the nodes are not redirected. This way, they can
  // work with unpublished nodes.
  // This is what you would use instead in that case:
  // if ($node->status == NODE_NOT_PUBLISHED && !user_access('administer nodes')) {
  // This will work for ALL users on the site, including the administrators.
  if ($node->status == NODE_NOT_PUBLISHED) {
    drupal_goto('<front>', array('query' => array('errCode' => 1)));

  // Let the core node handler serve the request otherwise.
  return node_page_view($node);


  1. You should do this through a custom module instead of the theme.
  2. Bear in mind that this might interfere with functionality of other modules, as well as workflows. See my comments and alternative version of the code.
  3. Use drupal_goto() for redirection instead of setting the location in header.

Hope this helps.

  • I will try this. Part of the confusion for me is the labelling of menu for routing items, thanks for the answer Aram. (And I will use a module :-) ).
    – jnelson
    May 19, 2016 at 13:26
  • $node-> status on the frontend only returns 0 or 1 I think btw. NODE_UNPUBLISHED has only appeared for me as part of hook_node_update(). Please update your example you have a chance Aram. Thank you again!
    – jnelson
    May 19, 2016 at 14:09
  • I updated the answer, but because I misspelled the name of the constant - it should be NODE_NOT_PUBLISHED instead. It's best practice to use that instead of 0/1. Let me know if this makes sense. May 19, 2016 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.