【问题标题】:ZF2 redirect() not working while header location doesZF2 重定向()在标头位置起作用时不起作用
【发布时间】:2013-09-07 11:21:51
【问题描述】:

我有一个带有索引操作的控制器,我在其中使用重定向路由:

$this->redirect()->toRoute('dummy-route')->setStatusCode('301');

这适用于我的本地开发机器,但是一旦我将它部署到暂存重定向就不再起作用了。 我设置了一个 header('Location: ') 只是为了查看重定向是否正常工作并且它是否按预期工作。

什么会导致 zf2 重定向无法在第二台机器上工作?

@noobie-php 是的,这是代码:

public function indexAction()
{
    $this->redirect()->toRoute('base-calculator')->setStatusCode('301');
    exit;
}

还有路线:

'application' => array(
            'type'    => 'Literal',
            'options' => array(
                'route'    => '/application',
                'defaults' => array(
                    '__NAMESPACE__' => 'Application\Controller',
                    'controller'    => 'Index',
                    'action'        => 'index',
                ),
            ),
            'may_terminate' => true,
            'child_routes' => array(
                'default' => array(
                    'type'    => 'Segment',
                    'options' => array(
                        'route'    => '/[:controller[/:action]]',
                        'constraints' => array(
                            'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                            'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                        ),
                        'defaults' => array(
                        ),
                    ),
                ),
            ),
        ),
                    'base-calculator' => array(
                            'type'    => 'Segment',
                            'options' => array(
                                    'route'    => '/calculate[/:criteriaFirst][/:criteriaSecond]',
                                    'constraints' => array(
                                            'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                            'id'     => '[0-9]+',
                                    ),
                                    'defaults' => array(
                                            'controller' => 'Application\Controller\Index',
                                            'action'     => 'calculator',
                                    ),
                            ),
                    )

【问题讨论】:

  • 你介意发布路线和动作

标签: php redirect zend-framework2


【解决方案1】:

前面有return 声明吗?

return $this->redirect()->to route('foo/bar');

/edit:好的,现在我知道你没有,这里解释一下。

该框架有一个称为短路的概念。这意味着每当您在路由或调度期间返回响应时,该响应将立即发送到客户端。这是在不渲染视图脚本等的情况下完成的,以加快速度。

Redirect 插件创建一个 Response 对象,其中设置了状态代码(为 301 或 302)并注入了 Location 标头。此位置标头包含您要重定向到的新网址。

如果您没有在此调用前面放置return,则会创建一个响应对象,但不会返回短路状态。它只是隐藏在框架内的某个地方。根据您自己的业务逻辑,您有时可能会被重定向,但大多数时候不会。

所以,就像the manual also points out,您必须使用return 才能使这种短路成为可能

【讨论】:

  • 重定向前我没有回报。我是不是该?总是乐于学习新事物,因此非常欢迎提供链接或解释。
  • 查看我的编辑。这只是一个疯狂的猜测,现在我知道你没有;这是解释:)
猜你喜欢
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2014-11-19
  • 2012-11-20
  • 2013-07-28
  • 2011-04-02
  • 1970-01-01
相关资源
最近更新 更多