核心是两步:关闭框架生成index.php($config['index_page'] = ''),并配置服务器重写规则(Apache用.htaccess,IIS用web.config)使请求正确转发至index.php。

去掉 CodeIgniter URL 中的 index.php,核心是两步:让框架不生成它,再让服务器能正确转发不带它的请求。只要配置到位,整个过程不难,但漏掉任一环节都会失败。
修改 config.php 关闭 index_page
这是第一步,也是最基础的一步。它告诉 CodeIgniter:别再往所有链接里自动加 index.php 了。
- 打开
application/config/config.php - 找到这一行:
$config['index_page'] = 'index.php'; - 改成:
$config['index_page'] = '';
改完后,site_url()、base_url() 等函数生成的链接就不再包含 index.php 了。
配置 .htaccess 实现 Apache 重写
仅改配置还不够——用户直接访问 /login,服务器得知道该交给 index.php 处理,否则会返回 404。这就靠 .htaccess 文件。
立即学习“PHP免费学习笔记(深入)”;
- 在项目根目录(和
index.php、application同级)新建或编辑.htaccess - 填入标准规则(推荐使用带条件判断的版本):
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
说明:
– 前两行条件确保真实存在的文件(如 style.css)和目录(如 uploads/)不被重写;
– 最后一行把其他所有请求都转给 index.php,并保留原始路径作为查询参数。
确认 Apache 的 rewrite 模块已启用
.htaccess 要生效,Apache 必须允许它起作用,且 mod_rewrite 模块已加载。
- 检查
httpd.conf中是否启用模块:LoadModule rewrite_module modules/mod_rewrite.so(前面不能有#) - 找到网站对应目录的
<Directory>块,把AllowOverride None改为AllowOverride All - 改完记得重启 Apache(
sudo systemctl restart apache2或httpd)
IIS 用户:用 web.config 替代 .htaccess
如果你部署在 Windows IIS 上,.htaccess 不起作用。需改用 web.config:
- 同样把
$config['index_page'] = '';设为空 - 在项目根目录新建
web.config,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="CI IndexPHP" stopProcessing="true">
<match url="^(.*)$" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php?{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
保存后刷新即可生效,无需重启 IIS(但部分共享主机可能需要等待缓存更新)。



















