php – codeigniter 隱藏或省略 index.php

參考了

http://rritw.com/a/bianchengyuyan/PHP/20121126/260390.html

在codeigniter新增了.htaccess後放入

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

發現不行!

原來最後一行少了一個.

應該是

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

這是我後來參考了 http://www.codeigniter.org.tw/forum/viewtopic.php?f=6&t=48

將.htaccess改用

DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index.php|images|css|js|robots.txt|favicon.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php/$1 [L,QSA]

為了搜尋引擎SEO著想,強制將預設的方訪倒向錯誤

引用如下

但問題是,你按原來的帶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的鏈接了,是不是很方便呢?
至於自定義錯誤頁面,你可以放置網站的地圖方便用戶定位,或者放置有個性的圖片說明,這就看你的創意了


最後去config.php把

$config[‘index_page’] = ‘index.php’;

改成

$config[‘index_page’] = ”;

 

 


Comments

發表迴響