Redirect when it is in URL

I solved the topic to get redirected to login page when someone is trying to open a post directly without login.
The user will be redirected to login page like this.

http://www.mypage.com/users/login?redirectUrl=%2Fposts%2Fview%2F8

But when user is logged in, then he should be automatically redirected to the page gibven in parameter redirectURL.
How can I do this. Should this be implemented in login function?
Thanks

If somebody opens this URL (the login page with a redirect in it) directly when they are already logged in? Why would somebody do that? Where do you expect such a link to be, apart from generated exactly when they need it?

Maybe I explained it in a wrong way.
This is the link I send in an email

http://www.mypage.com/posts/view/8

And when someone click on the link and got to this page, he will be automatically forwarded to the login page, because the user is not authenticated. So far so good.
But after successfully login, then the user should come back to the page where the link was pointing on.
And as you can see on my link before, the redirectUrl is already given in the URL, automatically.
Bute for now, when I successfully logged in, I will come to the standard page and not to the redirectUrl in the parameter.
How can I do this or should this be automatically?
Thanks

Does your login function look like the provided example, specifically the redirect when there is a valid result?

the redirect is not done automatically. You need to tell it. See whether the debug($redirect) gives you the url. Output from debug should be like /posts/view/8

Assuming you are using cakephp 5

$redirect = $this->request->getQuery('redirect') ?? '/home' ;  // Option 1. Redirects to 'home' if no referrer found
debug($redirect); // should output /posts/view/8
$redirect = $this->Authentication->getLoginRedirect() ?? '/home';   // Option 2. Redirects to 'home' if no referrer found
debug($redirect);   // should output /posts/view/8
return $this->redirect($redirect);

If you use the default auth way as documented, this would automatically be built in and be activated.
The code should be sth like shown above using $this->Authentication->getLoginRedirect().

Thanks for your hint.
I added the redirectURL in my login function.
I check if redirectURL is not empty and redirect to this URL.