手把手教你如何去掉CodeIgniter URL中的index.php

时间:2017-07-27
相信网上关于如何去掉CodeIgniter URL中index.php的文章非常多,本文章结合网上资料和自己所学习的CodeIgniter知识点,向大家介绍CodeIgniter如何去掉URL中的index.php,需要的朋友可以参考一下。

利用动态网页技术生成的技术大都含有index.php,在不引起路由混乱的前提下,有效删除URL中的inde.php可以让网页地址看起来更友好!以下篇幅虽针对CI框架而言,但从其实现原理来看,对其他情况下类似问题的解决仍然是有较大参考价值的.

首先,你要清楚自己的 Web 服务器是 Apache,支持 mod_rewrite,并且已经配置好 rewrite 相关的参数。 

什么是 rewrtie 可以 Google 一下。

然后,在 CI 根目录(与index.php同级) 下新建立一个配置文件,命名为: .htaccess 

在里面这样写:

RewriteEngine on  
RewriteCond $1 !^(index\.php|images|robots\.txt)  
RewriteRule ^(.*)$ /index.php/$1 [L]

然后,将CI中配置文件(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'] = '';

ok,完成。还要记得重启apache。

但在实践中,以上方案仅适用于与运行于Apache环境下的服务器且并不具有充分的普遍适用性!当CI程序位于非根目录或位于某些虚拟主机上时,以上解决方案会引起”404错误”或”no input file specified”等错误.百度参考过相关问题的解放方案后,找到了一种具有通用性的有效删除URL路径中index.php的方法,代码参考如下:

当index.php不在根目录时,你可以在index.php所在目录里新建.htaccess文件并使用以下代码:

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txtl)
RewriteRule ^(.*)$ /path_to_app/index.php?/$1 [L]

注意把path_to_app换成你的index.php所在文件的目录.假设你的index.php放在根目录的tool子文件夹下,你可以这样写:

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txtl)
RewriteRule ^(.*)$ /tool/index.php?/$1 [L]

以上方案应该可以解决Apache环境下如何有效删除URL中index.php的问题,如果有其他问题,请评论或留言并留下一个有效的联系方式.我会尝试替您解决并将可能的解决方案及时通知您!