CakePHP 3.X中的自定义404页面 [英] Custom 404 page in CakePHP 3.X

查看:60
本文介绍了CakePHP 3.X中的自定义404页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为进入生产环境网站的所有错误创建一个自定义404页面。例如,如果我收到缺少的控制器或查看错误,则它将重定向到
http://example.com/404.html,。在某些情况下,我也会故意重定向它 http://example.com/404.html

I want to create one custom 404 page for all errors coming to the website for production environment. For example if I receive missing controller or view error then it will redirect to http://example.com/404.html, Also in some cases I will deliberately redirect it http://example.com/404.html

在CakePHP 2.x的早期版本中通过在AppContoller.php中添加以下操作来完成

Earlier in CakePHP 2.x it was done by adding following action in AppContoller.php

public function appError($error) {
    $this->redirect('/page-not-found.html',301,false);
} 

但是在CakePHP 3.x中它不起作用,我想复制相同的内容CakePHP 3.x中的行为

But It is not working in CakePHP 3.x, I want to replicate same behavior in CakePHP 3.x

推荐答案

请勿重定向


采取的正确措施如果页面应呈现404,则是呈现404

重定向到另一个页面会使用户感到困惑,尤其是因为许多浏览器会缓存301响应,从而产生原始网址无法访问。这也会影响例如搜索引擎作为静态文件 404.html 的响应码为200(除非您修改了网络服务器配置),因此它会显示404,但根本不会。

Redirecting to another page is confusing for users, especially since many browsers cache 301 responses making the original url inaccessible. This also affects e.g. search engines as the static file 404.html will have a 200 response code (unless you modify your webserver config) so it'll say 404 but simply not be.

博客教程,所有开发人员在开始一个项目之前应做的事情,会引导您正确的方向:

The blog tutorial, which all devs should do before starting a project, guides you in the right direction:

public function view($id)
{
    $article = $this->Articles->get($id);
    $this->set(compact('article'));
}

表方法 get 返回单个实体对象或抛出异常

The table method get returns a single entity object or throws an exception:


如果get操作未找到任何结果,则会引发Cake\Datasource\Exception\RecordNotFoundException。您可以自己捕获此异常,也可以允许CakePHP将其转换为404错误。

If the get operation does not find any results a Cake\Datasource\Exception\RecordNotFoundException will be raised. You can either catch this exception yourself, or allow CakePHP to convert it into a 404 error.

此示例中的控制器代码不需要具有任何如果不存在该怎么办处理,因为默认情况下如果记录不存在,则结果为404。

The controller code in this example doesn't need to have any "what if it doesn't exist" handling because by default if the record doesn't exist the result is a 404.

如果您想更改404或500页的外观,请更改模板文件

If you want to change the way the 404 or 500 pages look change the template files


对于所有4xx和5xx错误,分别使用模板文件error400.ctp和error500.ctp。

For all 4xx and 5xx errors the template files error400.ctp and error500.ctp are used respectively.

错误模板为在您的应用程序中,请注意,在生产模式下输出非常小

The error template is in your application, note that in production mode the output is very minimal.

这篇关于CakePHP 3.X中的自定义404页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆