MODX Community

Howto redirect unauthorised page acces to login page?

Hi I have a site with a member section, i setup resource-groups and i installed the Login extra and it all works fine.
And when an unauthorised person acesses a page, i want him to be redirected to the login page.
So i used the unauthorized_page setting to hold the ID of the login page hoping the visitor would be redirected to the loginpage.
However this does not work; the visitor gets redirected to the 404 page.
I tried to make a small plugin to do the redirecting for me onHandleRequest

     if (!$modx->user->hasSessionContext($modx->context->get('key'))) {
         $url = $modx->makeUrl(162);
         $modx->sendRedirect($modx->makeUrl($url));
         return $url;
     }
  }

but that also redirects the visitor to 404.
How can i fix this
Tnx
RDG

1 Like

Hi @rdaneeel,

That’s odd… seems to be a cache issue. It is not the first time I do what you are trying to do.

Have you tried to clear cache and confirm after if /core/cache/ is empty?

1 Like

The sendRedirect() method can be unreliable in plugins. It’s more reliable to put it in a snippet and just put a tag for the snippet on the page or in a Template.

BTW, your return $url line will never execute. I’d suggest removing it and putting this at the very end (outside any braces):

return '';
1 Like

Have you set up permissions in such a way that anonymous users see the unauthorized page rather than the error page? See the “Unauthorized Versus Error Page” section here. With that in place, you do not need any plugin or snippet, just your unauthorized page to have a login form.

2 Likes

This same page “saved my life” two days ago.
When users receive the “no permissions” page, you can then include a login form. This same approach solved my problem.

1 Like