Removing URL Parameters and Redirecting in Magento
In this post, we’ll walk you through how to remove specific URL parameters in Magento, store them in session, and redirect back to the same page without those parameters.
The Challenge: Cleaning Up URLs Without Losing Data
Sometimes, marketing teams or external systems might append unnecessary parameters like utm_source to your Magento URLs. While these are useful for tracking, they clutter up the URL structure and look unprofessional. We want to remove them while still preserving the data for later use.
A Naive Approach: Incorrect Use of Event Observers
The provided code attempts to do this using a controller_front_init_before observer:
public function cleanParams(Varien_Event_Observer $observer)
{
$frontController = $observer->getEvent()->getFront();
$params = $frontController->getRequest()->getParams();
$myParams = array("b");
foreach($myParams as $myParam) {
if (isset($params[$myParam])) {
$customerSession->setData(
$myParam, $params[$myParam]
);
unset($params[$myParam]);
}
}
$frontController->getRequest()->setParams($params);
}
However, this approach has a critical flaw. After unsetting the parameters, it sets them back to the request object without actually redirecting anywhere. This leaves us with a clean URL in the address bar but doesn’t physically move the user or update their session.
The Correct Approach: Using Magento’s Built-in Redirect
To solve this properly, we need to use Mage::app()->getResponse()->setRedirect(). Here’s how:
public function cleanParams(Varien_Event_Observer $observer)
{
$request = $observer->getFrontController()->getRequest();
if ($request->has('b')) {
$customerSession->setData('b', $request->getParam('b'));
$request->unsParam('b');
}
Mage::app()->getResponse()->setRedirect($request->getUrl());
}
In this revised version, we first check if the ‘b’ parameter exists. If it does, we store its value in the customer session and then remove it from the request object using unsParam.
Finally, we set a redirect to the current URL using Mage::app()->getResponse()->setRedirect($request->getUrl()). This tells Magento to send an HTTP 302 status code instructing the browser to reload the page at the specified URL without the ‘b’ parameter.
Conclusion
Removing and preserving data from URL parameters is a common requirement in e-commerce platforms like Magento. By leveraging built-in functions and best practices, we can achieve this cleanly, efficiently, and without disrupting the user’s experience.
Remember, always test your changes thoroughly to ensure they don’t break other functionality or create new security vulnerabilities. If you’re looking for more advanced SEO techniques in Magento, consider checking out our Magento SEO Guide for a comprehensive overview.
Happy coding!