ZF2 重定向() 不起作用,而标头位置不起作用


ZF2 redirect() not working while header location does

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

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

这在我的本地开发计算机上有效,但是一旦我将其部署到暂存,重定向就不再起作用了。我设置了一个标题('位置:'),只是为了查看重定向是否正常工作并且它确实按预期工作。

是什么使 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',
                                    ),
                            ),
                    )
你前面

return语句吗?

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

/编辑:好的,现在我知道你还没有,这里有一个解释。

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

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

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

因此,正如手册还指出的那样,您必须使用return才能使这种短路成为可能