First of all I've seen lot's of threads about restriction, but didn't find what I'm looking for.

So, my goal is to restrict the access for a specific node to anonymous users and when they try to enter that node, it will redirect them to the user/login page.

I was using Content Access module till now. It works like it should, but the problem is when this module is enabled, block caching is not working. As I know the Context module has the same issue.

I have one big menu block and without caching, the website is 4 times slower. When the Content Access module is disabled, the block is cached and the performance is great.

Let's say the url of the page is 'apple'.

I'm looking for a way to restrict only this page programmatically, without breaking the block caching.

I'm using Drupal 7.

  • Have you considered simply setting the default 403 page to the user login, and restrict the node via a module? Some other options might be logintoboggan, or r4032login modules.
    – Geoff
    May 4, 2014 at 20:03

1 Answer 1



// Get the current active node object if present.
$node = menu_get_object();
// Redirect to login page if NID == 42 and user is anonymous.
// User will then go back to node page due to destination being set.
if (   user_is_anonymous() 
    && !empty($node) 
    && !empty($node->nid) 
    && $node->nid == 42
    ) {
  drupal_goto('user/login', array('query' => array('destination' => 'node/' . $node->nid)), 307);


$args = arg();
if (   user_is_anonymous()
    && isset($args[0]) && $args[0] == 'node'
    && isset($args[1]) && is_numeric($args[1])
    ) {
  drupal_goto('user/login', array('query' => array('destination' => 'node/' . $node->nid)), 307);
  • Where should I put that code, Mickey? I have a custom module, but do I have to call some hook for that? May 4, 2014 at 21:25
  • I would use hook_init.
    – mikeytown2
    May 4, 2014 at 21:29
  • I think should be <a href="api.drupal.org/api/drupal/modules!system!system.api.php/…> because hook_init is not run in cached pages. Or use hook_init but avoid caching of that node page.
    – sanzante
    May 4, 2014 at 21:32
  • It works great, Mickey. I think you should edit your answer with adding hook_init(), so I can mark your answer. I've just tested, it doesn't break the block caching. Thank you very much! May 4, 2014 at 21:37
  • Just to correct, you have a syntax error. This line should have another parentheses after the letter 307, so it's gonna be like this: drupal_goto('user/login', array('query' => array('destination' => 'node/' . $node->nid), 307)); May 4, 2014 at 21:52

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.