Reputation: 511
Following problem: Under certain circumstances i want the user to be redirected to default page not found page of magento.
Therefore i declared an event observer with the following code.
Mage::app()->getFrontController()->getResponse()->setHeader('HTTP/1.1','404 Not Found',true);
Mage::app()->getFrontController()->getResponse()->setHeader('Status','404 File not found',true);
$pageId = Mage::getStoreConfig('web/default/cms_no_route');
$url = rtrim(Mage::getUrl($pageId),'/');
Mage::app()->getFrontController()->getResponse()->setRedirect($url);
The redirect is working fine, but the given HTTP status code is 302 Found and not 404 Not Found. Any hints what i did wrong?
Upvotes: 0
Views: 9728
Reputation: 2481
The official Magento way to do this:
$this->getResponse()->setHeader('HTTP/1.1','404 Not Found');
$this->getResponse()->setHeader('Status','404 File not found');
$pageId = Mage::getStoreConfig(Mage_Cms_Helper_Page::XML_PATH_NO_ROUTE_PAGE);
if (!Mage::helper('cms/page')->renderPage($this, $pageId)) {
$this->_forward('defaultNoRoute');
}
I copied this code from the noRouteAction
function in /app/code/core/Mage/Cms/controllers/IndexController.php
.
I used it inside a controller of a custom module, and it works. Magento version: 1.7.0.2.
Upvotes: 4
Reputation: 1443
Do you return
immediately after setRedirect()
? If any output is sent after setRedirect()
was called then redirect headers will eventually be ignored.
Remember that exit
will not let the redirect headers sent either, unless you call sendResponse()
before exit
as @benmarks mentioned.
Upvotes: 1
Reputation: 23205
The main issue is
Mage::app()->getFrontController()->getResponse()->setRedirect($url);
setRedirect()
[link] accepts a second parameter for the response code; by default it is 302.
Upvotes: 1