
CodeIgniter 报“404 Page Not Found”通常并非路由配置错误,而是因未定义 index() 方法或默认路由未指向有效方法所致;本文详解如何通过补全控制器入口、规范路由映射和验证 URL 访问路径来快速解决该问题。
codeigniter 报“404 page not found”通常并非路由配置错误,而是因未定义 `index()` 方法或默认路由未指向有效方法所致;本文详解如何通过补全控制器入口、规范路由映射和验证 url 访问路径来快速解决该问题。
在 CodeIgniter 中,“404 Page Not Found”错误看似由 .htaccess 或 routes.php 引起,但实际根源常在于 控制器缺少必需的入口方法。根据你提供的代码,routes.php 设置了:
$route['default_controller'] = 'Crud';
这等价于访问 http://yourdomain.com/index.php/Crud(或去除 index.php 后的对应路径),而 CodeIgniter 会自动尝试调用 Crud 控制器中的 index() 方法。但你的 Crud.php 中并未定义 public function index() —— 只有 savedata() 方法,因此系统找不到可执行的默认动作,直接触发 404。
✅ 正确解决方案(二选一)
方案一:添加 index() 方法(推荐)
为 Crud 控制器补充 index() 入口,作为默认展示页(例如跳转到注册表单):
// application/controllers/Crud.php
public function index()
{
$this->load->view('insert'); // 直接加载 insert 表单页
}
此时访问根路径(如 http://localhost/yourapp/)即可正常显示表单,无需修改路由。
方案二:显式指定默认方法
若希望默认直接执行 savedata(不推荐用于 GET 请求,但可用于调试),修改路由:
// application/config/routes.php $route['default_controller'] = 'Crud/savedata'; // 显式指向方法
⚠️ 注意:savedata() 当前逻辑混合了视图渲染与表单提交处理(即 GET 显示 + POST 处理),但直接通过 index.php/Crud/savedata 访问时是 GET 请求,$this->input->post() 为空,将跳过插入逻辑并仅显示表单——这虽能避免 404,但语义混乱。更合理的做法是分离职责:
public function index()
{
$this->load->view('insert');
}
public function savedata()
{
if ($this->input->method() === 'post') {
$data = [
'first_name' => $this->input->post('first_name'),
'middle_name' => $this->input->post('middle_name'),
'last_name' => $this->input->post('last_name'),
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'confirmpassword' => $this->input->post('confirmpassword'),
'birthday' => $this->input->post('birthday'),
'email' => $this->input->post('email'),
'contactnumber' => $this->input->post('contactnumber')
];
$result = $this->Crud_model->saverecords($data);
$this->output->set_content_type('text/plain')->set_output(
$result ? 'Records Saved Successfully' : 'Insert error !'
);
} else {
show_404(); // 非 POST 请求禁止直接访问
}
}
同时更新表单 action 以匹配标准 RESTful 路径:
<!-- application/views/insert.php -->











