小十的个人博客

@小十

born for design, do what you want, and carpe diem

文章 343
朋友 17
来访 1840

LATEST POSTS

RANKINGS

    • http://www.xiaoten.com
    • 网站成立5376天

    小十

    • 努力著

    整合 WordPress 与七牛云存储 CDN 加速服务

    想对博客的图片进行加速,使用七牛云的镜像加速功能,只需下面几步即可实现要求:

    第一步:创建七牛公开空间


     

    第二步:设置镜像存储

    成功建立空间之后,打开该空间的【镜像存储】页面。

    在【域名设置】下,我们知道了该空间的默认域名,你也可以绑定自己的域名,这里不展开讨论。

    在【镜像存储】下,点击【一键加速网站】按钮,在弹出的对话框中,【镜像源】填写你的博客地址,确定即可。

    第三步:添加 WordPress 代码

    在 WordPress 主题目录下的 functions.php 文件中,加入以下代码实现替换功能:

    if ( !is_admin() ) {
    	add_action('wp_loaded','xiaoten_ob_start');
    	
    	function xiaoten_ob_start() {
    		ob_start('xiaoten_qiniu_cdn_replace');
    	}
    	
    	function xiaoten_qiniu_cdn_replace($html) {
    		$local_host = 'https://www.xiaoten.com'; //博客域名
    		$qiniu_host = 'https://old.xiaoten.com'; //七牛域名
    		$cdn_exts   = 'js|css|png|jpg|jpeg|gif|ico'; //扩展名(使用|分隔)
    		$cdn_dirs   = 'wp-content|wp-includes'; //目录(使用|分隔)
    	
    		$cdn_dirs   = str_replace('-', '\-', $cdn_dirs);
    
    		if ($cdn_dirs) {
    			$regex	=  '/' . str_replace('/', '\/', $local_host) . '\/((' . $cdn_dirs . ')\/[^\s\?\\\'\"\;\>\<]{1,}.(' . $cdn_exts . '))([\"\\\'\s\?]{1})/';
    			$html =  preg_replace($regex, $qiniu_host . '/$1$4', $html);
    	} else {
    			$regex	= '/' . str_replace('/', '\/', $local_host) . '\/([^\s\?\\\'\"\;\>\<]{1,}.(' . $cdn_exts . '))([\"\\\'\s\?]{1})/';
    			$html =  preg_replace($regex, $qiniu_host . '/$1$3', $html);
    		}
    		return $html;
    	}
    }

    上述三步即可完成,当然,如果你的需求还包括加速远程图片或刷新缓存等,那么还是老老实实安装七牛镜像存储 WordPress 插件吧。

    Comments | 2 条评论

      游客,你好 修改资料

    *邮箱和昵称必须填写