使用_remap()函数。这允许您对404错误执行一些非常强大的操作,这些操作超出了通常内置的范围,例如
- Different 404 messages depending if the user is logged in or not!
- Extra logging of 404 errors - you can now see what the referring person was to the 404, thus helping track down errors. This includes seeing if it was a bot (such as Google bot) - or if it was a logged in user, which user caused the 404 (so you can contact them for more information - or ban them if they are trying to guess admin routes or something)
- Ignore certain 404 errors (such as a precomposed.png error for iPhone users).
- Allow certain controllers to handle their own 404 errors different if you have a specific need (i.e. allow a blog controller to reroute to the latest blog for example)
让您的所有控制器扩展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 ;
但是welcome中有否my_404()
函数-这意味着你的所有404都将通过_remap
如果你在逻辑中使用show_404()
或只是redirect(my_404)
,这取决于你。如果你使用show_404()
,那么只需修改Exceptions类即可重定向
class MY_Exceptions extends CI_Exceptions
{
function show_404($page = , $log_error = TRUE)
{
redirect( my_404 );
}
}