---
title: "CodeIgniter框架全面去除URL中的index.php"
author: "marx"
date: "2012-11-25T20:35:08Z"
tags: []
categories: ["Web前端"]
slug: "codeigniter-url-index-php"
draft: false
lastmod: "2013-02-21T23:41:32Z"
id: 1734837
url: "https://marx.iteye.com/blog/1734837"
---

CodeIgniter框架的所有入口都是index.php, 比如http://localhost/index.php/controller/action/parameters

 

那么如何省略掉URL 上的 index.php, 让URL更简化：http://localhost/controller/action/parameters

 

有以下两大步：

 

1\. 通过.htaccess 文件重写, 这里假设你的apache 已经支持重写以及支持.htaccess文件了，并且可以正常访问CI框架。

.htaccess内容如下 ：

 

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

 .htaccess文件的好处是修改后不用重启服务即可生效。

 

到这里第一步完成了， 再去浏览器试试http://localhost/controller/action/parameters (这是演示路径，具体是你的测试地址），去掉了index.php访问正常。

 

但问题是，你按原来的带index.php的路径去访问，依然可以访问。

那么这就是不全面去除了，因为用户还可以输入带index.php路径访问你的页面， 这样对搜索引擎SEO也不好，因为搜索引擎可能会收录了两种页面地址， 这样分散权重。彻底去除，我们可以看下面第二步：

 

2\. CI框架提供了非常灵活的扩展机制，用户可以在application的相应目录里扩展系统的类，CI会优先去读application里的类，如果没有找到，再去读系统默认的类。

 

这里我们在application/core里新建立一个MY\_Controller.php文件扩展系统的CI\_Controller,这个MY\_前缀是可以在application/config/config.php配置文件里修改的。扩展类代码如下：

 

```
<?php

class MY_Controller extends CI_Controller {
	
	public function __construct(){
		parent::__construct();
		$this->dealWithIndexPage();
	}
	
	protected function dealWithIndexPage(){
		$uri = $this->input->server('REQUEST_URI',true);
		//deal with index.php
		if(strpos($uri,'index.php')!==false){
			$this->load->helper('url');
			redirect('/error/');
		}
	}
}
```

 这里我们将所有的URL上带有index.php的路径跳转到我们自定义的错误页面，这样就不会再出现带index.php的链接了，是不是很方便呢？

至于自定义错误页面，你可以放置网站的地图方便用户定位，或者放置有个性的图片说明，这就看你的创意了 :)