去除CodeIgniter URL中index.php的完整配置指南
在CodeIgniter框架中,默认的URL结构通常包含入口文件,例如当项目部署在/CodeIgniter/目录下时,访问二级页面会呈现为http://localhost/CodeIgniter/index.php/welcome的形式。这种带有index.php的路径不仅显得冗余,也不利于SEO和用户体验,因此需要对其进行优化以移除该部分。
第一步是调整Web服务器Apache的配置,具体操作是打开conf/httpd.conf文件。
在该配置文件中找到LoadModule rewrite_module modules/mod_rewrite.so这一行,并删除其前面的注释符号#,从而启用URL重写模块。
接着在文件中搜索AllowOverride None指令(注意配置中可能存在多处),根据相关注释指引,将与.htaccess相关的设置改为AllowOverride All,以允许使用覆盖配置。
第二步是在CodeIgniter项目的根目录下创建.htaccess文件,该位置与index.php和system文件夹同级。由于直接创建可能受限,建议先新建一个记事本文件,保存时命名为.htaccess即可。具体内容可参考CI官方手册。
以下是推荐的.htaccess配置代码:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
若项目未部署在Web服务器的根目录,而是位于子目录如http://www.nowamagic.net/CodeIgniter/,则上述第三行的RewriteRule需调整为RewriteRule ^(.*)$ /CodeIgniter/index.php/$1 [L],以确保路径正确映射。
此外,如果index.php同级目录下还存在js、css等静态资源文件夹,为避免被错误重定向,需在第二行的RewriteCond中将这些目录加入排除列表,修改为RewriteCond $1 !^(index\.php|images|js|css|robots\.txt)。
第三步是修改CodeIgniter的配置文件,路径为system/application/config/config.php。找到$config['index_page'] = "index.php";这一行,将其值修改为空字符串,即$config['index_page'] = "";。
配置示例如下所示:
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
*/
$config['index_page'] = '';
完成所有配置更改后,必须重启Apache服务以使新的重写规则生效。