【发布时间】:2012-06-04 18:09:58
【问题描述】:
我的任务是强制我们所有的 404 页面返回 301 的 http 状态。我一直在网上搜索/阅读,但找不到任何有关如何完成此操作的信息。
有没有办法改变 layout.xml 或模板文件中的 http 状态?如果没有,我应该看什么控制器?
【问题讨论】:
标签: php magento http-status-code-301 http-status-codes
我的任务是强制我们所有的 404 页面返回 301 的 http 状态。我一直在网上搜索/阅读,但找不到任何有关如何完成此操作的信息。
有没有办法改变 layout.xml 或模板文件中的 http 状态?如果没有,我应该看什么控制器?
【问题讨论】:
标签: php magento http-status-code-301 http-status-codes
Magento 中有很多 404 页面,Alan Storm 的这篇文章应该可以帮助您找到所需的内容:
【讨论】:
根据上面提到的article,CMS 无路由页面(或 defaultNoRoute 操作)都使用以下代码从控制器操作设置其 404 标头
$this->getResponse()->setHeader('HTTP/1.1','404 Not Found');
如果你看一下setHeader的方法定义
#File: lib/Zend/Controller/Response/Abstract.php
public function setHeader($name, $value, $replace = false)
{
$this->canSendHeaders(true);
$name = $this->_normalizeHeader($name);
$value = (string) $value;
if ($replace) {
foreach ($this->_headers as $key => $header) {
if ($name == $header['name']) {
unset($this->_headers[$key]);
}
}
}
$this->_headers[] = array(
'name' => $name,
'value' => $value,
'replace' => $replace
);
return $this;
}
你可以看到第三个参数$replace,你可以用它再次设置一个标题值,所以像这样
Mage::app()->getResponse()->setHeader('HTTP/1.1','...header text...',true);
应该足以更改标头的值。只需在前端控制器告诉响应对象发送其输出之前调用它。您可能可以从 phtml 模板执行此操作(因为在发送之前呈现输出),但更好的方法是使用两个 CMS 无路由操作的事件侦听器(如果您为无路由设置了自定义操作,相应调整)
controller_action_postdispatch_cms_index_noRoute
controller_action_postdispatch_cms_index_defaultNoRoute
【讨论】:
我最终完成了 3 个步骤:
首先,我创建了一个新的 cms 页面(404/登陆)并从我的 404 页面复制了所有 cms 设置。这是我将用户重定向到的页面。
然后我创建了一个新模块(您可以使用 Alan Storm http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-3-magento-controller-dispatch 编写的这个很棒的指南)并使用以下操作:
public function indexAction() {
$url = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)."404/landing"; //build url
$this->getResponse()->setRedirect($url, $code = 301); //set a redirect using Zend response object
}
一旦我的模块和登录页面正常工作,我只需将默认无路由 URL(系统 -> 配置 -> 网络 -> 默认页面)更改为我的新模块。
【讨论】:
我没有看太多,但 404 消息似乎是在这个文件中发送的 - 在 3 个函数中:
服务器路径: /app/code/core/Mage/Cms/controllers
我将标头从 404 更改为 301 重定向。可能不是最漂亮的解决方案,但它似乎有效。
**/**
* Default index action (with 404 Not Found headers)
* Used if default page don't configure or available
*
*/
public function defaultIndexAction()
{
$this->getResponse()->setHeader('HTTP/1.1, 301 Moved Permanently');
$this->getResponse()->setHeader('Location','http://www.streetcred.dk');
}
/**
* Render CMS 404 Not found page
*
* @param string $coreRoute
*/
public function noRouteAction($coreRoute = null)
{
$this->getResponse()->setHeader('HTTP/1.1, 301 Moved Permanently');
$this->getResponse()->setHeader('Location','http://www.streetcred.dk');
}
/**
* Default no route page action
* Used if no route page don't configure or available
*
*/
public function defaultNoRouteAction()
{
$this->getResponse()->setHeader('HTTP/1.1, 301 Moved Permanently');
$this->getResponse()->setHeader('Location','http://www.streetcred.dk');
}**
【讨论】:
$baseurl=Mage::getUrl('',array('_nosid'=>true)); 获取基本网址