您的位置:首页 > 其它

wordpress静态文件加速,整合CDN

2015-12-17 14:40 351 查看
最近公司的一个网上商店的项目,用的底层是wordpress+woocommerce,里面很多自定义的额外功能是由我开发的,最后部署的时候计划整合CDN,把静态内容都分流给边缘服务器,wordpress只处理数据逻辑,也就是只运行php程序。
这涉及到如何把默认的静态资源url替换成CDN的url,在网上翻了一遍,原来已经有大牛写出了靠谱的插件了,这个大牛的博客地址

https://dannyvankooten.com/using-a-cdn-with-wordpress/
人家在github上已经开源了自己的项目

https://github.com/dannyvankooten/wp-cdn-loader

直接下载插件到wp-content/plugins,解压,在管理页面激活就能使用
https://github.com/dannyvankooten/wp-cdn-loader/archive/master.zip
首先要在wp-config.php里面添加这么一行,可以作为是否开启CDN的开关之一,另外一个开关就是在后台
关闭这个插件的功能咯~

define( 'DVK_CDN_URL', 'http://xxxxxx.cloudfront.net' );
//The plugin won't replace assets when SCRIPT_DEBUG is enabled.
配置好之后,刷新页面,就能看到所有css,js,jpg,png的url的前面都被替换成了设置的值(
http://xxxxxx.cloudfront.net
)了,说明配置成功!
好奇心所向,研究了人家写的代码,一共2个文件,主文件
<?php
/*
Plugin Name: CDN Loader
Description: This plugin will load your assets from a given CDN instead of the local server.
Author: Danny van Kooten
Version: 1.0
Author URI: https://dannyvankooten.com/ */

namespace CDN_Loader;

if( ! defined( 'ABSPATH' ) ) {
exit;
}

add_action( 'template_redirect', function() {

// Don't run if SCRIPT_DEBUG is set to true
if( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
return;
}

// load class
require_once __DIR__ . '/src/UrlRewriter.php';

// get url of cdn & site
$cdn_url = ( defined( 'DVK_CDN_URL' ) ? DVK_CDN_URL : '' );
$site_url = get_site_url();

// instantiate class
$url_rewriter = new UrlRewriter( $cdn_url, $site_url );
$url_rewriter->add_hooks();
});
class库文件
<?php

namespace CDN_Loader;

class UrlRewriter {
/**
* @var string
*/
private $cdn_url = '';

/**
* @var string
*/
private $site_url = '';

/**
* Constructor
*
* @param string $cdn_url
* @param string $site_url
*/
public function __construct( $cdn_url, $site_url ) {
// Store cdn url & site url in property
$this->site_url = $site_url;
$this->cdn_url = $cdn_url;
}

public function add_hooks() {

// add nothing if cdn url is empty
if( '' === $this->cdn_url ) {
return false;
}

// add rewrite filters for plugin & theme assets
add_filter( 'theme_root_uri', array( $this, 'rewrite' ), 99, 1 );
add_filter( 'plugins_url', array( $this, 'rewrite' ), 99, 1 );

// add rewrite filters for misc scripts and styles
add_filter( 'script_loader_src', array( $this, 'rewrite' ), 99, 1 );
add_filter( 'style_loader_src', array( $this, 'rewrite' ), 99, 1 );
return true;
}

/**
* @param $url
*
* @return mixed
*/
public function rewrite( $url ) {
$url = str_replace( $this->site_url, $this->cdn_url, $url );
return $url;
}
}
今天先写到这里,公司要上班了, 有空再补充说明。

本文出自 “安家圈子交流学习” 博客,请务必保留此出处http://brucetam.blog.51cto.com/1863614/1725648
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: