I have a route set up in routes.php that calls a controller action using something similar to what is described here: https://straightupcraft.com/articles/how-do-i-setup-a-route-to-point-to-a-controller-action-instead-of-a-template

This works much better for my purposes than POSTing a form to the controller. However, I'm not sure how best to handle redirects. Ideally I would like to redirect back to the page where the user clicked on the link, but calling


doesn't work when using a route like this. The URL just remains the URL as defined in the route.

Is there a different method I can use to make sure users are returned to the page where they were when they clicked the link?

2 Answers 2


You're mistaken about how redirectToPostedUrl works... That's designed to redirect from a form submission, when the redirect field was supplied:

<input type="hidden" name="redirect" value="page/to/redirect/to"> 

What you really want is this:


The request->getUrlReferrer method will actually retrieve the originating page URL.

  • Yup, I knew redirectToPostedUrl wasn't what I needed, but just wasn't quite sure where to turn. This looks like exactly what I needed though, thank you!
    – John O
    Commented Oct 14, 2015 at 23:54
  • Cool, no problem! :)
    – Lindsey D
    Commented Oct 14, 2015 at 23:58
  • Note that request->getUrlReferrer actually uses the request headers from the browser, so you cannot assume that it exists and/or is reliable 100% of the time. To ensure you redirect back to the appropriate page you will need to include that hidden "redirect" input in your form.
    – Jordan Lev
    Commented Jun 20, 2017 at 21:59

In case you need this for CraftCMS version 3, as I did today, the code slightly changed:


This works fine with version 3.

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.