Created
September 10, 2014 19:04
-
-
Save wernerkrauss/6f2019e127d4ab60d11a to your computer and use it in GitHub Desktop.
CDN rewrite in Page_Controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Page_Controller extends ContentController | |
{ | |
private static $cdn_domain = 'cdn.mysite.com'; | |
private static $cdn_rewrite = false; | |
public function handleRequest(SS_HTTPRequest $request, DataModel $model = null) | |
{ | |
$response = parent::handleRequest($request, $model); | |
if (!Director::isDev() && $body = $response->getBody()) { | |
$body = self::replaceCDN($body); | |
$response->setBody($body); | |
} | |
return $response; | |
} | |
static function replaceCDN($body) | |
{ | |
if (!Config::inst()->get('Page_Controller', 'cdn_rewrite')) { | |
return; | |
} | |
if (!$body) { | |
return; | |
} | |
if (Versioned::current_stage() == 'dev') { | |
return; | |
} | |
$cdn = Config::inst()->get('Page_Controller','cdn_domain'); | |
$body = str_replace('src="/assets/', 'src="' . $cdn . '/assets/', $body); | |
$body = str_replace('src=\"/assets/', 'src=\"' . $cdn . '/assets/', $body); | |
$body = str_replace('href="/assets/', 'href="' . $cdn . '/assets/', $body); | |
$body = str_replace(Director::absoluteBaseURL() . 'assets/', $cdn . '/assets/', $body); | |
return $body; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now refactored as a module: https://github.com/wernerkrauss/silverstripe-cdnrewrite