You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter默认控制器与.htaccess配置问题:URL访问异常求助

CodeIgniter 3.1.13 移除index.php后无默认控制器URL无法访问的解决办法

问题描述

使用CodeIgniter 3.1.13,已通过.htaccess配置移除URL中的index.php,但只有包含默认控制器(Welcome)的URL能正常访问:

可正常访问的URL:

  • https://www.example.com
  • https://www.example.com/index.php
  • https://www.example.com/welcome
  • https://www.example.com/welcome/page/test

无法访问的URL:

  • https://www.example.com/page/test

当前配置文件内容

.htaccess文件

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

#force https
RewriteCond %{HTTP_HOST} example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]
</IfModule>

<IfModule !mod_rewrite.c>

# Without mod_rewrite, route 404's to the front controller
ErrorDocument 404 /index.php

</IfModule>

config.php修改内容

$config['base_url'] = 'https://www.example.com/';
$config['index_page'] = '';

Welcome.php控制器内容

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

function __construct()
{   
    parent::__construct();
}

function index()
{
    $this->load->view('homepage', $data);
}

function page($pageName)
{
    $data['content'] = $this->load->view($pageName, '', TRUE);
    $this->load->view('template_page', $data);
}

}

解决办法

方法1:配置路由规则(推荐)

在application/config/routes.php中添加路由映射,把page/test这类URL直接指向Welcome控制器的page方法:

// 匹配单个参数的page请求
$route['page/(:any)'] = 'welcome/page/$1';

// 如果需要支持多参数(比如page/test/123),可以追加:
$route['page/(:any)/(:num)'] = 'welcome/page/$1/$2';

这种方式精准可控,不会影响其他控制器的正常访问。

方法2:修改.htaccess规则(备选)

如果希望所有不带控制器名的URL都默认走Welcome控制器,可以调整RewriteRule:

RewriteRule ^(.*)$ index.php/welcome/$1 [L]

注意:这种方式会让所有未匹配到现有控制器/路由的请求都指向Welcome控制器,可能干扰其他业务逻辑,需谨慎使用。

额外检查项

  1. 确认服务器已开启mod_rewrite模块,且Apache配置中网站根目录的AllowOverride已设为All,否则.htaccess规则无法生效。
  2. 测试前清除浏览器缓存,避免旧URL缓存导致结果异常。

内容的提问来源于stack exchange,提问作者vinceo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 11:20:37