Skip to content

Instantly share code, notes, and snippets.

@wernerkrauss
Created September 10, 2014 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wernerkrauss/6f2019e127d4ab60d11a to your computer and use it in GitHub Desktop.
Save wernerkrauss/6f2019e127d4ab60d11a to your computer and use it in GitHub Desktop.
CDN rewrite in Page_Controller
<?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;
}
}
@wernerkrauss
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment