Blair Wadman 2 minute read

Redirect users to the login form if access is denied

Out of the box Drupal will display a simple Access Denied message is a user is trying to access content that they do not have permission to. This is not exactly user friendly. A better solution is to redirect the user to the login form and when the user logs in, redirect them back to the content that they want to see. There are two main ways to achieve this.

Option 1: Add some code to page.tpl.php

The first option is to add a simple block of code to the very top of your page template file (page.tpl.php). The code is:


&lt;?php<br /> if ($title == 'Access denied') {<br /> header( 'Location: /user?destination=' . substr ($_SERVER['REQUEST_URI'],1 ) ); <br />} ?&gt;';

The $title variable is the meta title for the page. This would normally be "Access denied" if a user does not have permission to view the content. The if statement simply says, if the meta title is equal to "Access denied" then redirect the user to the user login form (sitename.com/user). It will also send the page that the user is trying to access. Therefore, once the user has logged in, he/she will be redirected back to that page.

This is a nice and simple way of achieving our goal. However, there is one problem with it. If you have caching switched on, the site may cache the access denied message if a user does not remember his/her correct login details. If that happens, subsequent users will get the access denied message.

Option 2: Logintobogan

The second option is to install the Login Toboggan module. The Login Toboggan module will display the login form for Access denied pages (must be set on in the settings). This option works with caching. The Login Toboggan module does other nice things as well, like allowing users to login with their email address instead of username.