CI框架实现控制器作为域名或者二级域名访问

Codeigniter的URI还没那么强大,要实现将二级域名绑定到某个控制器上,还得动点手脚。要实现的结果是将
http://www.z1988.com/admin => http://admin.z1988.com
http://www.z1988.com/member => http://m.z1988.com
来访问。 首先你要确保域名泛解析了。泛域名解析是存在一定危害的,所以你要:

在application/config/下建立一个domain.php文件,这里面放你要解析的子域名(对应CI控制器)

[php]
$domain = array(
'admin.z1988.com'=>'admin',
'm.z1988.com'=>'member',
);
[/php]

然后修改system/core/URI.php的_set_uri_string方法:
如果配置中二级域名或域名不存在就404错误吧,这样就避免了泛解析的危害。
[php]
protected function _set_uri_string($str)
{
// Filter out control characters and trim slashes
$this->uri_string = trim(remove_invisible_characters($str, FALSE), '/');
//绑定域名访问url
include(APPPATH.'config/domain.php');
$server_name = $_SERVER['SERVER_NAME'];
if (isset($domain[$server_name])) {
if( $domain[$server_name] != '' ){
$this->uri_string = '' . $domain[ $server_name ] .'/'. $this->uri_string;
}
}else{
show_404();
}

if ($this->uri_string !== '')
{
// Remove the URL suffix, if present
if (($suffix = (string) $this->config->item('url_suffix')) !== '')
{
$slen = strlen($suffix);

if (substr($this->uri_string, -$slen) === $suffix)
{
$this->uri_string = substr($this->uri_string, 0, -$slen);
}
}

$this->segments[0] = NULL;
// Populate the segments array
foreach (explode('/', trim($this->uri_string, '/')) as $val)
{
$val = trim($val);
// Filter segments for security
$this->filter_uri($val);

if ($val !== '')
{
$this->segments[] = $val;
}
}

unset($this->segments[0]);
}
}
[/php]

阅读剩余
THE END