使用_remap()函数。这允许你做一些非常强大的404错误超出通常内置的错误 - 例如
- 不同的404消息,取决于用户是否登录!
- 额外记录404错误 - 您现在可以看到引荐人对404的影响,从而帮助追踪错误。这包括查看它是否是机器人(例如Google bot) - 或者它是登录用户,哪个用户造成了404(因此您可以联系他们获取更多信息 - 或者如果他们试图猜测管理路线或其他)
- 忽略某些404错误(例如iPhone用户的precomposed.png错误)。
- 允许,如果你有特殊需要一定的控制器来处理自己的404错误不同(即允许博客控制器重新路由到例如最新的博客)
把所有的控制器扩展MY_Controller
:
class MY_Controller extends CI_Controller
{
// Remap the 404 error functions
public function _remap($method, $params = array())
{
// Check if the requested route exists
if (method_exists($this, $method))
{
// Method exists - so just continue as normal
return call_user_func_array(array($this, $method), $params);
}
//*** If you reach here you have a 404 error - do whatever you want! ***//
// Set status header to a 404 for SEO
$this->output->set_status_header('404');
// ignore 404 errors for -precomposed.png errors to save my logs and
// stop baby jesus crying
if (! (strpos($_SERVER['REQUEST_URI'], '-precomposed.png')))
{
// This custom 404 log error records as much information as possible
// about the 404. This gives us alot of information to help fix it in
// the future. You can change this as required for your needs
log_message('error', '404: ***METHOD: '.var_export($method, TRUE).' ***PARAMS: '.var_export($params, TRUE).' ***SERVER: '.var_export($_SERVER, TRUE).' ***SESSION: '.var_export($this->session->all_userdata(), TRUE));
}
// Check if user is logged in or not
if ($this->ion_auth->logged_in())
{
// Show 404 page for logged in users
$this->load->view('404_logged_in');
}
else
{
// Show 404 page for people not logged in
$this->load->view('404_normal');
}
}
然后在routes.php
设置你的404的到你的主控制器,到功能不存在 - 即
$route['404'] = "welcome/my_404";
$route['404_override'] = 'welcome/my_404';
但在欢迎NOmy_404()
功能 - 这意味着你的所有404的将通过_remap
功能 - 让你实现干,有你的所有404的逻辑在一个地方。
如果您在逻辑中使用show_404()
或只是redirect('my_404')
,那么它取决于您。如果你使用show_404()
- 那么只需要修改例外类重定向
class MY_Exceptions extends CI_Exceptions
{
function show_404($page = '', $log_error = TRUE)
{
redirect('my_404');
}
}
可能重复自定义404错误页面创建:http://stackoverflow.com/questions/8422033/codeigniter-2 -1-issue-with-show-404-and-404-override –