Redirect To Previous Page After Customer Login

Do you want to let only customers to access a page in your store? Let's see how you can force a customer to login before visiting a page and then redirect back to that page.

First of all we will create a module for this blog post and name it MageVision_Blog24. Then we need to define frontend route. So let's create a route.xml like below.

Afterwards we have to create a controller called it post and an action named called index. So to access the page you have the request the following url:

The response will be an empty page but before reaching the page, you will be redirected to the customer login page. After a successful login your will be redirected back to the page. To achieve that we have to use the dispatch function in our action class Index.php. As we can see in the code below, before calling the parent dispatch function, we check if the customer is logged in. If not, using the setBeforeAuthUrl function from the customer session model, we set the url that the customer will be redirected after a successful login. in our case is the blog24/post/index.

The full example as extension can be found here.

Feel free to share this post and ask your questions in the comments below.

Till next time!