Basic Redirect Patterns
Magento provides multiple redirect methods.
Redirect to URL:
// External URL
return $this->_redirect('https://example.com/page');
// Internal URL
return $this->_redirect('vendor_module/controller/action');
// With parameters
return $this->_redirect('vendor_module/post/view', [
'id' => $post->getId(),
'_current' => true // Keep current params
]);
Redirect back (to referrer):
// Redirect to previous page
return $this->_redirect($this->_redirect->getRedirectUrl());
// Or use Referer URL
$refererUrl = $this->_objectManager->get(
\Magento\Framework\Url\Interface::class
)->getEncodedUrl();
return $this->_redirect($refererUrl);
Redirect to referer:
public function execute()
{
// Get referer URL
$refererUrl = $this->getRequest()->getServer('HTTP_REFERER');
if ($refererUrl) {
return $this->_redirect($refererUrl);
}
// Fallback
return $this->_redirect('*/*/index');
}
Redirect with ResultFactory:
public function execute()
{
$redirect = $this->resultFactory->create(
\Magento\Framework\Controller\Result\Redirect::class
);
$redirect->setPath('vendor_module/controller/action', ['id' => $id]);
return $redirect;
}
Redirect with Messages
Pass success/error messages across redirects.
Success message:
public function execute()
{
try {
$this->service->save($data);
$this->messageManager->addSuccessMessage(__('Saved successfully'));
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
return $this->_redirect('*/*/index');
}
Messages persist across redirect:
// Messages are stored in session
// They appear on the redirected page
$this->messageManager->addSuccessMessage(__('Product saved'));
return $this->_redirect('*/*/view', ['id' => $id]);
// User sees: "Product saved" on the view page
Clear messages:
// Clear all messages before redirect
$this->messageManager->getMessages(true);
return $this->_redirect('*/*/index');
Custom message with URL:
$this->messageManager->addSuccessMessage(
__('Saved. <a href="%1">View product</a>', $this->_url->getUrl('*/*/view', ['id' => $id]))
);
return $this->_redirect('*/*/index');
Conditional messages:
if ($this->isFirstTime()) {
$this->messageManager->addNoticeMessage(__('This is your first time'));
}
if ($hasWarnings) {
$this->messageManager->addWarningMessage(__('Please review warnings'));
}
Redirect with Cookies
Set cookies that persist across redirects.
Set cookie before redirect:
public function execute()
{
// Set cookie
$cookieManager = $this->_objectManager->get(
\Magento\Framework\Stdlib\Cookie\CookieManagerInterface::class
);
$cookieManager->setCookie(
'last_category',
$categoryId,
[
'path' => '/',
'lifetime' => 86400 * 30 // 30 days
]
);
return $this->_redirect('*/*/view', ['id' => $id]);
}
Read cookie and redirect:
public function execute()
{
$lastCategory = $this->getRequest()->getCookieValue('last_category');
if ($lastCategory) {
return $this->_redirect('catalog/category/view', ['id' => $lastCategory]);
}
return $this->_redirect('*/');
}
Session-based redirects:
public function execute()
{
$session = $this->_objectManager->get(
\Magento\Framework\Session\SessionManagerInterface::class
);
// Store redirect URL in session
$session->setData('redirect_url', $this->getRequest()->getRequestUri());
// Later, retrieve and redirect
$redirectUrl = $session->getData('redirect_url');
if ($redirectUrl) {
$session->unsData('redirect_url');
return $this->_redirect($redirectUrl);
}
return $this->_redirect('*/*/index');
}
Redirect Security and Best Practices
Security considerations and best practices for redirects.
Prevent open redirect:
public function execute()
{
$redirectUrl = $this->getRequest()->getParam('redirect');
// Validate redirect URL
if ($redirectUrl && $this->isInternalUrl($redirectUrl)) {
return $this->_redirect($redirectUrl);
}
return $this->_redirect('*/*/index');
}
private function isInternalUrl(string $url): bool
{
$host = parse_url($url, PHP_URL_HOST);
$currentHost = $this->storeManager->getStore()->getBaseUrl();
return $host && strpos($currentHost, $host) !== false;
}
PRG pattern (Post/Redirect/Get):
// Prevents duplicate form submission
public function execute()
{
if ($this->getRequest()->isPost()) {
$this->service->save($this->getRequest()->getParams());
$this->messageManager->addSuccessMessage(__('Saved'));
// Redirect (not render page)
return $this->_redirect('*/*/view', ['id' => $id]);
}
// GET: Show form
return $this->pageFactory->create();
}
Redirect with referrer:
public function execute()
{
try {
$this->deleteItem();
$this->messageManager->addSuccessMessage(__('Deleted'));
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
// Return to list or previous page
$referer = $this->getRequest()->getServer('HTTP_REFERER');
return $this->_redirect($referer ?: '*/*/index');
}
Best practices:
1. Always use PRG pattern for form submissions
2. Validate redirect URLs to prevent open redirects
3. Use _redirect() for simple redirects
4. Use ResultFactory\Redirect for complex scenarios
5. Always include messages before redirect
6. Prefer internal redirects over external URLs
Quiz
1. What pattern prevents duplicate form submissions?
2. How do you redirect back to the previous page?
3. How do you pass messages across redirects?
4. What security concern exists with redirects?
Flashcards
Question
How do you redirect to a controller action?
Click to reveal answer
Answer
$this->_redirect('vendor_module/controller/action', ['id' => $id])
Question
What pattern prevents duplicate submissions?
Click to reveal answer
Answer
PRG (Post/Redirect/Get)
Question
How do you pass messages across redirects?
Click to reveal answer
Answer
$this->messageManager->addSuccessMessage() before redirect
Question
How do you redirect to external URL?
Click to reveal answer
Answer
$this->_redirect('https://example.com')
Question
How do you prevent open redirect?
Click to reveal answer
Answer
Validate redirect URL is internal
Revision Notes
Key Takeaways
- 1. Use _redirect() for simple redirects
- 2. Use ResultFactory\Redirect for complex scenarios
- 3. PRG pattern prevents duplicate form submissions
- 4. Messages persist in session across redirects
- 5. Validate redirect URLs to prevent open redirects
- 6. Cookies can be set before redirects
Interview Tips
- • Explain the PRG pattern and why it's important
- • Describe how to pass messages across redirects
- • Discuss open redirect security vulnerabilities
- • Know different redirect methods available
Cheat Sheet
Redirect Patterns Cheat Sheet
Basic redirect:
return $this->_redirect('route/action', ['id' => $id]);
Redirect back:
return $this->_redirect($this->_redirect->getRedirectUrl());
With messages:
$this->messageManager->addSuccessMessage(__('Done'));
return $this->_redirect('*/*/index');
PRG pattern:
if ($this->getRequest()->isPost()) {
// Process
return $this->_redirect('*/*/view');
}
return $this->pageFactory->create();
Security: Validate redirect URLs, prevent open redirect