六月 23rd, 2010

让thinkphp 支持二级域名

在官方手册去查了下,没有具体说明怎么支持二级域名的方法,最后找到一个解决方案(修改thinkphp的parsePathInfo函数让其支持二级域名)。

# 修改的路径是:
# ThinkPHP\Lib\Think\Util\Dispatcher.class.php
private static function parsePathInfo()
{
	$pathInfo = array();
	if(C('URL_PATHINFO_MODEL')==2){
		$paths = explode(C('URL_PATHINFO_DEPR'),trim($_SERVER['PATH_INFO'],'/'));
 
		$APP_LEVEL_DOMAINS = false;
		$domain = array_shift(explode('.',$_SERVER['HTTP_HOST']));
 
		if(in_array($domain, C('APP_LEVEL_DOMAINS'), true)){
			$APP_LEVEL_DOMAINS = true;
		}
 
		if(C('APP_LEVEL_DOMAIN_DEPLOY_ON') && $APP_LEVEL_DOMAINS) {
			if(isset($paths[0]) && strtolower($paths[0]) == strtolower($domain)){
				array_shift ($paths);
			}
			$pathInfo[C('VAR_MODULE')] = ucfirst(array_shift(explode('.',$_SERVER['HTTP_HOST'])));
			$pathInfo[C('VAR_ACTION')] = array_shift($paths);
		} else {
			$groupApp = C('APP_GROUP_LIST');
			if ($groupApp) {
				$arr = array_map('strtolower',explode(',',$groupApp));
				$pathInfo[C('VAR_GROUP')] = in_array(strtolower($paths[0]),$arr) 
								? array_shift($paths) : '';
			}
			$pathInfo[C('VAR_MODULE')] = array_shift($paths);
			$pathInfo[C('VAR_ACTION')] = array_shift($paths);
		}
		for($i = 0, $cnt = count($paths); $i < $cnt; $i++){
			if(isset($paths[$i+1])) {
				$pathInfo[$paths[$i]] = (string)$paths[++$i];
			}elseif($i==0) {
				$pathInfo[$pathInfo[C('VAR_ACTION')]] = (string)$paths[$i];
			}
		}
	}else {
		$res = preg_replace('@(\w+)'.C('URL_PATHINFO_DEPR').'([^,\/]+)@e', 
			'$pathInfo[\'\\1\']="\\2";', $_SERVER['PATH_INFO']);
	}
	return $pathInfo;
}

用上面这个函数替换后就能支持二级域名了,不过还有事情要做。在项目的配置文件(config.php)里面加上二级域名支持。

return array(
	#'配置项'=>'配置值'
	'DEBUG_MODE' => true,
	'URL_MODEL' => 2,
	'APP_LEVEL_DOMAIN_DEPLOY_ON' => true, #标识打开二级域名支持
	'APP_LEVEL_DOMAINS' => array('sites','seo'), #例:如果是sites.ys250.com 那么将采用2级别域名的方式
	#'URL_HTML_SUFFIX'=>'.html',
	#'URL_ROUTER_ON' => true


结果如:
http://www.ys250.com/sites/ip (old)
http://sites.ys250.com/ip (new)
http://www.ys250.com/seo (old)
http://seo.ys250.com (new)
http://ips.ys250.com/ 让采用老的方式,因为ips没有开通二级支持支持,因此大家要开通自己的二级域名请设置APP_LEVEL_DOMAINS这个数组。
本文参考自:http://www.c1991.com/article/163.html

One Response to “让thinkphp 支持二级域名”

  1. 你这个功能是不错的,不知官方啥情况。

Write A Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">