CodeIgniter泛域名解析与二级域名路由实现
近期有一个项目需求是利用二级域名以提升SEO效果。由于项目基于CodeIgniter框架构建,尽管该框架具备灵活的路由机制,但默认无法直接支持二级域名功能。在查阅大量资料并进行多次测试后,总结出一套可行的解决方案。本示例以假想域名www.mysite.com为例进行说明。
第一步: 首先需要在httpd.conf配置文件中创建虚拟主机(virtualhost)。
ServerAdmin admin@163.com
DocumentRoot "D:/www/cms"
ServerName www.mysite.com
ServerAlias *.mysite.com #这里采用泛解析的方式
ErrorLog "logs/mysite.com-error.log"
CustomLog "logs/mysite.com.log" common
第二步: 期望达到的访问效果如下: http://www.mysite.com/category/news/1.html =====> http://category.mysite.com/news/1.html 为确保能正常访问该域名,必须对hosts文件进行修改。
127.0.0.1 www.mysite.com
127.0.0.1 category.mysite.com
第三步: 需要修改system/core/URI.php文件中的_set_uri_string方法。
/**
* Set the URI String
*
* @access public
* @param string
* @return string
*/
function _set_uri_string($str)
{
// Filter out control characters
$str = remove_invisible_characters($str, FALSE);
// If the URI contains only a slash we'll kill it
$this->uri_string = ($str == '/') ? '' : $str;
// Add by fengyun for url rewrite at 2013-1-25 1:02:27
@include(APPPATH.'config/domain'.EXT);
$arrServerName = explode('.', $_SERVER['SERVER_NAME']);
if (in_array($arrServerName[0], $domain)) {
$this->uri_string = '/' . $arrServerName[0]."/" . $this->uri_string;
}
}
此步骤的主要目的是让URL能够被CodeIgniter框架正确解析和理解。
第四步:在application/config目录下新建一个domain.php文件,其内容结构如下:
<?php
if ( ! defined('BASEPATH'))
exit('No direct script access allowed');
$domain = array('category',"detail","info","archive");
至此,基本功能已经实现。不过,当使用site_url()函数生成链接时,若需指向二级域名,则需要进行额外的特殊处理。