【问题标题】:Redirecting to 404 route in PhalconPHP results in Blank Page在 PhalconPHP 中重定向到 404 路由会导致空白页面
【发布时间】:2016-03-29 18:01:17
【问题描述】:

我已经设置了一个路由器,并在其中为 404 定义了一条路由:

<?php

use Phalcon\Mvc\Router;
$router = new Router(FALSE);
$router->removeExtraSlashes(true);

$route = $router->add('/', ['controller' => 'index', 'action' => 'index']);
$route->setName("index");

// other routes defined here...

$router->notFound([
  "controller" => "index",
  "action" => "route404"
]);

?>

我的索引控制器:

<?php

class IndexController extends ControllerBase
{

    public function indexAction()
    {
    // code removd for berevity 
    }

    public function route404Action() {
      // no code here, I just need to show the view.
    }

}
?>

我有一个视图 @/app/views/index/route404.phtml,其中只有一点 HTML,我什至尝试将其设为 .volt 文件,但不走运。

当我转到一个与任何路由都不匹配的页面时,它可以正常工作。但是,如果我尝试重定向到它,我只会得到一个空白页。例如,在我的一个控制器中,我有这个:

if (!$category) {
  // show 404

  //Tried this next line to test, and it indeed does what you'd expect, I see "Not Found". 
  // echo "Not Found"; exit;  

  $response = new \Phalcon\Http\Response();
      $response->redirect([
    "for" => "index", 
    "controller" => "index", 
    "action" => "route404"]
  );

  return; // i return here so it won't run the code after this if statement.
}

有什么想法吗?该页面完全空白(源代码中没有任何内容),并且我的 apache 日志中没有错误。

【问题讨论】:

    标签: phalcon phalcon-routing


    【解决方案1】:

    尝试返回响应对象,而不仅仅是一个空白返回。示例:

    return $this->response->redirect(...);
    

    但是我建议使用从调度员转发来显示 404 页面。这样,用户将停留在相同的 url 上,浏览器将收到正确的状态码 (404)。这种方式对 SEO 也很友好 :)

    例子:

    if ($somethingFailed) {
        return $this->dispatcher->forward(['controller' => 'index', 'action' => 'error404']);
    }  
    
    // Controller method
    function error404Action()
    {   
        $this->response->setStatusCode(404, "Not Found"); 
        $this->view->pick(['_layouts/error-404']);
        $this->response->send();
    }    
    

    【讨论】:

    • 优秀的答案!你的推荐正是我想要的!我最终在 ControllerBase 中添加了一个notFound() 方法,以便更容易从多个控制器/位置使用。谢谢! =)
    • 很高兴我提供了帮助,向前你用一块石头打了两只兔子:为用户提供更多的可用性,让那些 seo 专家高兴:)
    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    相关资源
    最近更新 更多