在项目开发中,我们常常会使用到cdn,但是呢,浏览器针对单个域名只能同时发起2个请求,这就造成了空有大量带宽,但是处理时间却还是很长。
为了解决这个问题,常常会对cdn域名建立多个二级域名,来解决浏览器同域名限制2个并发的问题。
这里我使用的ci框架
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); //如果未定义站点cdn二级路径名称,则自行定义之 if (!defined('SITE_CDN_NAME')) { define('SITE_CDN_NAME', 'app'); } //如果未定义站点cdn域名,则自行定义之 if (!defined('SITE_CDN_DOMAIN')) { define('SITE_CDN_DOMAIN', '.xs8xs8.cn'); } /** * 获取CDN相关资源地址 */ class cdn{ public function expires($min) { $expires = $min*60; header("Pragma: public"); header("Cache-Control: maxage=" . $expires); header("Expires: " . gmdate("D, d M Y H:i:s", TIMESTAMP + $expires) . " GMT"); } /** * 获取资源文件CDN路径 * 例如: * http://book.xs8.cn/static/js/jquery.js * 传递参数时需传递jquery.js * @param string $filename * @param bool $global 是否获取共用文件 * @return string */ public function get_resources($filename, $global = false) { $path_parts = pathinfo($filename); $ext = strtolower($path_parts['extension']); if (in_array($ext, array('js', 'css'))) { $method = 'get_cdn_' . $ext; return $this->$method($filename, $global); } else if (in_array($ext, array('jpg', 'jpeg', 'gif', 'png', 'bmp'))) { return $this->get_cdn_img($filename, $global); } else if (in_array($ext, array('swf', 'flv'))) { return $this->get_cdn_flash($filename, $global); } else { return SITE_URL . $path; } } private function get_cdn_pre_config($filename, $global) { $site_cdn_name = $global == false ? SITE_CDN_NAME : 'www'; $url_pre = sprintf("%u", crc32(md5(strtolower($filename)))) % 4 + 1; //若要生成s1和s2则代码改为:%2+1 return array('site_cdn_name' => $site_cdn_name, 'url_pre' => $url_pre); } public function get_cdn_js($filename, $global = false) { $cdn_config = $this->get_cdn_pre_config($filename, $global); $url = 'http://s' . $cdn_config['url_pre'] . SITE_CDN_DOMAIN . '/' . $cdn_config['site_cdn_name'] . '/js/' . $filename; return $url; } public function get_cdn_css($filename, $global = false) { $cdn_config = $this->get_cdn_pre_config($filename, $global); $url = 'http://s' . $cdn_config['url_pre'] . SITE_CDN_DOMAIN . '/' . $cdn_config['site_cdn_name'] . '/css/' . $filename; return $url; } public function get_cdn_img($filename, $global = false) { $cdn_config = $this->get_cdn_pre_config($filename, $global); $url = 'http://s' . $cdn_config['url_pre'] . SITE_CDN_DOMAIN . '/' . $cdn_config['site_cdn_name'] . '/images/' . $filename; return $url; } public function get_cdn_flash($filename, $global = false) { $cdn_config = $this->get_cdn_pre_config($filename, $global); $url = 'http://s' . $cdn_config['url_pre'] . SITE_CDN_DOMAIN . '/' . $cdn_config['site_cdn_name'] . '/flash/' . $filename; return $url; } }