Header Redirect In Magento Index.php
I know its a bit weird but in some cases you may want to use a header redirect in your Magento’s index.php – perhaps you have multiple website views and one of them needs a holding page? There’ll be some scenario out there that may require it and we just so happened to come across one today – the splitting of website views.
Essentially what we wanted to do was split domain1.co.uk and domain2.co.uk into two separate Magento instances rather than their current website views. While this was taking place we needed to serve up a holding page for one of the domains – however because for the meantime they both route through the index.php we wanted to separate them out there.
When doing a vhost config website view (easier than it sounds), you’ll probably be familiar with the following .htaccess line:
SetEnvIf Host www\.domain2\.co.uk MAGE_RUN_CODE=domain2websiteid
What that does is check where we are coming from and sets a superglobal variable or $_SERVER variable.
Now what we’d normally do at this point is just stick the following at the top of the index.php to route it away from Magento to our holding page (while leaving the other domain traffic loading the Magento store) however when we try this nothing happens – no redirect it just loads our website view again… Is our if statement working? Have headers already been sent?
if(stristr($_SERVER['MAGE_RUN_CODE'] == "domain2websiteid"){
header('Location: hold.php'); // redirect to holding page for this website view
}
Well it is working and headers have not yet been sent, the problem occurs because we are still activating the Mage::run command. So the simple fix for this is to place your Mage::run inside an else statement.
if($_SERVER['MAGE_RUN_CODE'] == "domain2websiteid"){
header('Location: hold.php'); // redirect to holding page for this website view
} else {
Mage::run($mageRunCode, $mageRunType);
}
I’m pretty sure the above code will also work if you were matching your $_SERVER['HTTP_HOST'] variable.
Rob is Ecommerce Web Design’s lead PHP developer, and an expert at customising the Magento framework to create completely unique sites. Follow him on twitter (because he's a twit) http://twitter.com/kent_robert. - Read my other posts.
