Drupal - How can I return a 404 error page in a node view?

Drupal permission system provides fine grained permission control for "create", "edit", "delete" actions for every node content type, but viewing action is covered by general "View published content" permission option that covers all content types.

In order to deny access to anonymous users when they are trying to view a node of certain content type, you need to include a function in a custom module that implements hook_node_access():

/**
 * Implements hook_node_access().
 *
 * Disallow anonymous user to view nodes of type "EXAMPLE".
 */
function MYMODULE_node_access($node, $op, $account) {
  if (user_is_anonymous() && $op == 'view' && $node->type == 'EXAMPLE') {
    return NODE_ACCESS_DENY;
  }
}

You need to replace MYMODULE with the module name that contains this function and EXAMPLE with the name of the content type that you wish to deny access to.

UPDATE: The code above would in fact return 403 (Access Denied) page, I'm sorry for confusion. The following code will return 404 (Page Not Found) page (only when user is trying to access the node of content type "example" in "full" view mode (usually by accessing the node by URL "node/NID]":

/**
 * Implements hook_node_view().
 *
 * Disallow anonymous user to view nodes of type "EXAMPLE".
 */
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if (user_is_anonymous() && $view_mode == 'full' && $node->type == 'EXAMPLE') {
    drupal_not_found();
    drupal_exit();
  }
}

Tags:

Nodes

Users