Search code examples
htmlmagentohttp-redirectblock

Magento redirect from HTML Block


Im want to redirect in my custom html block to specific urls.

What i'm trying:

class Mage_Page_Block_Html_World extends Mage_Core_Block_Template {
function __construct()
{
    $i = 0;
    parent::__construct();
    $this->setTemplate('page/html/world.phtml');
    $this->setCookie();
}

public function setCookie()
{
    $lang = $this->getLanguageCode();
    if(isset($_GET['country'])) {
        $country = $_GET['country']; 
        Mage::getModel('core/cookie')->set('country', $country);
    } else {
        $country = Mage::getModel('core/cookie')->get('country');
    }
    /*Redirect to cookie url*/
    if($country) {
        try {
            $url = "http://myurl.dev/".$country."/";
            Mage::app()->getFrontController()->getResponse()->setRedirect($url);
        } catch (Exception $e) {
            echo 'Exception: ',  $e->getMessage(), "\n";
        }
    }
}

Because i use a multistore configuration in my .htaccess i use:

SetEnvIf Host www.myurl.dev MAGE_RUN_CODE=base
SetEnvIf Host www.myurl.dev MAGE_RUN_TYPE=website
SetEnvIf Host ^myurl.dev MAGE_RUN_CODE=base
SetEnvIf Host ^myurl.dev MAGE_RUN_TYPE=website

SetEnvIf Host www.myurl1.dev MAGE_RUN_CODE=vs
SetEnvIf Host www.myurl1.dev MAGE_RUN_TYPE=website
SetEnvIf Host ^myurl1.dev MAGE_RUN_CODE=vs
SetEnvIf Host ^myurl1.dev MAGE_RUN_TYPE=website

The Issue: With this redirect i get the Error 310: Too many redirects. I can't figure out how to fix this.


Solution

  • Too many redirect suggests an infinite loop. It sounds like you are loading this block on every page - which means even once the user is redirected, the block is loaded again and still trys to redirect them.

    I would suggest your check for country needs to be changed:

    if($country) {
    

    this check needs to fail once the user has been redirected, to avoid another redirect being sent, currently it looks like it's returning true even after the redirect.