Перед тем, как предпринимать какие-либо шаги создайте резервные копии файлов и базы данных. Плагин интеграции с CDN предназначен только для сайтов работающих по стандартным шаблонам CMS. Если вы вносили изменения в логику работы CMS, плагин может не cработать.
В инструкции описано как создать плагин, который интегрирует CSS, JS и файлов изображений (.jpg, .png и .gif) с CDN. Плагин совместим с MODX Revolution.
2. Войдите в ваш MODX используя панель
3. Перейдите на вкладку Elements и создайте плагин.
4. Заходим в «элементы» и создать плагин.
5. Скопируйте этот код в новый плагин и измените переменную «zoneurl» на CDN-домен или «Персональный домен» (CNAME), который задали в личном кабинете при создании ресурса. Проверьте работает ли ваш домен, прежде чем использовать ее для интеграции.
<?php
class SkyparkCDN {
var $zoneurl; // zone url from the SkyparkCDN dashboard
var $cdncache = array(); // assets already tested to be on SkyparkCDN
var $ttl; // in seconds
function __construct($output, &$modx) {
$this->modx = $modx;
// zone url or zonealias
$this->zoneurl = 'http://*********.r.worldcdn.net';
// define lifetime of the cached asset in the modx cache
$this->ttl = 86400; // 1 day before testURL again
// get already cached images
$this->cdncache = $this->modx->cacheManager->get('cdncache');
if(!is_array($this->cdncache)) {
$this->cdncache = array();
}
}
function linkAssets($output) {
// adjust local images, css and js files
$output = preg_replace_callback('|<img(?:.+?)src\=\"(\S+)\"|', array($this ,'getURL'), $output);
$output = preg_replace_callback('|<link(?:.+?)href\=\"(\S+)\"|', array($this ,'getURL'), $output);
$output = preg_replace_callback('|<script(?:.+?)src\=\"(\S+)\"|', array($this ,'getURL'), $output);
$this->modx->cacheManager->set('cdncache', $this->cdncache, $this->ttl);
return $output;
}
function getURL($match) {
if( !stripos($match[1], '.js') && !stripos($match[1], '.css') && !stripos($match[1], '.jpg') && !stripos($match[1], '.png') && !stripos($match[1], '.gif') || stripos($match[1], '//') !== false ) {
return $match[0];
} else {
$replace = $match[1]; // URL to replace
if(array_key_exists($replace, $this->cdncache)) {
$replaced = $this->cdncache[$replace];
return str_replace($replace, $replaced, $match[0]);
} else {
$replaced = $this->zoneurl.( substr($match[1], 0, 1) == '/' ? '' : '/' ).$match[1]; // create SkyparkCDN URL for asset
if( $this->testURL($replaced) ) {
$this->cdncache[$replace] = $replaced; // add to cache
return str_replace($replace, $replaced, $match[0]);
} else {
return $match[0];
}
}
}
}
function testURL( $link ) {
$url_parts = @parse_url( $link );
if ( empty( $url_parts["host"] ) ) return( false );
if ( !empty( $url_parts["path"] ) ) {
$documentpath = $url_parts["path"];
} else {
$documentpath = "/";
}
if ( !empty( $url_parts["query"] ) ) {
$documentpath .= "?" . $url_parts["query"];
}
$host = $url_parts["host"];
$port = $url_parts["port"];
if (empty( $port ) ) {
$port = "80";
}
$socket = fsockopen( $host, $port, $errno, $errstr, 30 );
if (!$socket) {
return(false);
} else {
fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
$http_response = fgets( $socket, 22 );
if ( stripos($http_response, "200 OK") ) {
return(true);
fclose( $socket );
} else {
return(false);
}
}
}
}
$output = &$modx->resource->_output;
$skyparkcdn = new SkyparkCDN($output, $modx);
$output = $skyparkcdn->linkAssets($output);
6. Активируйте системное событие «OnWebPagePrerender» и нажмите сохранить.
Интеграция с CDN завершена! Рекомендуем проверить html-код сайта, чтобы убедиться, что URL-адреса были верно изменены.
Для этого нажмите F12 или откройте «Инструменты разработчика», перейдите на вкладку Network, обновите страницу. В ссылках на статические файлы, вы должны увидеть CNAME-запись из личного кабинета, вместо вашего доменного имени.