0

I want to add a simple redirect if a customer is not logged in when trying to access one of my categories.

Now, I have created a test.phtml file and added it in my theme page/test.phtml with fallowing content:

<?php
    if(!Mage::getSingleton('customer/session')->isLoggedIn()){
      echo "Not logged in";
      Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getBaseUrl().'customer/account/login/');
    } else {
      echo "Logged in";
    }
?>

Then created a static block in admin panel with following:

{{block type="core/template" template="page/test.phtml"}}

In the Admin > Catalog > Manage Categories, I seleceted the category I want the redirect to be in and in Display Setting > Display Mode I changed it to Static Block and Products and assigned the block to it. Flushed cache.

Everything works as intended. When I navigate to the category as not-signed customer, I get redirected to log in page. However, if I navigate to the category again, I can see the products and the message "Logged in".

If I refresh the cache, the redirect works again.

Can anyone tell me why?

If this is expected behaviour, is there alternative method of redirecting customer if they not logged in and trying to access on of my categories?

  • Are you using some FPC plugin? – Shoaib Munir Feb 6 at 15:02
  • I use Varnish for caching – Greg Feb 6 at 15:08
1

In short you need to hole punch your block to avoid varnish caching the block. I assume as you use Magento 1.9.x. , you mush have installed Varnish Turpentine extension (if not i insist you should be).

After that name your block to uinquely identify it.

{{block name="your_block_name" type="core/template" template="page/test.phtml"}}

After that in your layout file, assume local.xml , add these lines below and save it. Your block will not be cached by varnish anymore. Hope this helps.

<reference name="your_block_name">
    <action method="setEsiOptions">
        <params>
            <access>private</access>
            <ttl>0</ttl>
        </params>
    </action>
</reference>
2

The first time you visit the page the block is not cached so the code in your block runs. The second time you visit the page the block has cached his output and won't run again.

I sugget you don't put redirects in the block html. But instead use events see this article for help

1

You can also add the information if the customer is logged in or not to the cache key of your block, that might work to. Just add the following two lines at the top of your template and give it a try:

$cacheKey = $this->getCacheKey();
$this->setCacheKey($cacheKey . Mage::getSingleton('customer/session')->isLoggedIn());

Better than putting that code in the template is of course to create a custom block with that logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.