CDN Versions

Is there a way to get a similar solution for CDN versions (not Cloudfront, Edgecast in this case) for js and css files as pretty neat by combining the Rewrite and PHP rule described in this stream ? I donโ€™t know how to make the PHP / mod-rewrite combination work on CDN, change my versions often and not perform manual routines. I use cookieless, a completely separate domain for serving static content, so I have to specify the full URL in the function.

For convenience, I will present the code from another thread here.

First, we use the following rewrite rule in .htaccess:

 RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-s # Make the file doesn't actually exist RewriteRule ^(.*)\.[\d]+\.(css|js)$ $1.$2 [L] # Strip out the version number 

Now we are writing the following PHP function:

 /** * Given a file, ie /css/base.css, replaces it with a string containing the * file mtime, ie /css/base.1221534296.css. * * @param $file The file to be loaded. Must be an absolute path (ie * starting with slash). */ function auto_version($file) { if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file)) return $file; $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file); return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file); } 

Now that we include our CSS, we change it:

 <link rel="stylesheet" href="/css/base.css" type="text/css" /> 

:

 <link rel="stylesheet" href="<?=auto_version('/css/base.css')?>" type="text/css" /> 

It will look like something similar, guaranteeing that the latest version will always be maintained, without having to update versions manually:

 <link rel="stylesheet" href="/css/base.1251992914.css" type="text/css" /> 

To make this work in an external CDN (in a completely different domain), I tried replacing

 <link rel="stylesheet" href="<?=auto_version('/css/base.css')?>" type="text/css" /> 

something like this ...

 <link rel="stylesheet" href="<?='http://cdn.externaldomain.com' . auto_version('/css/base.css')?>" type="text/css" /> 

But wrapping the function around the internal URL and adding the CDN domain does not work ...

+4
source share
2 answers

It turns out my solution:

 <link rel="stylesheet" href="<?= 'http://cdn.externaldomain.com' . auto_version('/css/base.css') ?>" type="text/css" /> 

works. I just missed a space in the code.

+3
source

Just a suggestion: See Aptimize

Version issues resolved. Many CDNs only perform periodic version checking, which means that pages can be served with outdated resources. Aptimize actively detects version changes and ensures that pages remain relevant, with a unique URL version control mechanism and aggressive browser caching of resources.

+1
source

Source: https://habr.com/ru/post/1340722/


All Articles