title: Versioning in a CDN
body: <p>Is there any way of achieving a similar versioning solution on a CDN (<em>not</em> Cloudfront, Edgecast in this case) for <code>js</code> and <code>css</code> files as the rather neat one, combining a Rewrite rule and PHP, described in <a href="https://stackoverflow.com/questions/118884/what-is-an-elegant-way-to-force-browsers-to-reload-cached-css-js-files">this thread</a>?  I don't know of a way of making that PHP/mod-rewrite combination work on a CDN, change my versions often, and don't want to do the versioning manually. I use a cookieless, entirely separate domain to serve static content, so I have to specify the full url in the function.</p>
  
  <p>For convenience I'll set out the code from the other thread here.</p>
  
  <p>First, we use the following rewrite rule in .htaccess:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Now, we write the following PHP function:</p>
  
  <pre><code>/**
   *  Given a file, i.e. /css/base.css, replaces it with a string containing the
   *  file's mtime, i.e. /css/base.1221534296.css.
   *  
   *  @param $file  The file to be loaded.  Must be an absolute path (i.e.
   *                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);
  }
  </code></pre>
  
  <p>Now, wherever we include our CSS, we change it from this:</p>
  
  <pre><code>&lt;link rel="stylesheet" href="/css/base.css" type="text/css" /&gt;
  </code></pre>
  
  <p>to this:</p>
  
  <pre><code>&lt;link rel="stylesheet" href="&lt;?=auto_version('/css/base.css')?&gt;" type="text/css" /&gt;
  </code></pre>
  
  <p>This will render as something of this kind, ensuring the latest version is always served, without having to update versions manually:</p>
  
  <pre><code>&lt;link rel="stylesheet" href="/css/base.1251992914.css" type="text/css" /&gt;
  </code></pre>
  
  <p>In order to get this working in an external CDN (on a totally different domain), I've tried to replace</p>
  
  <pre><code>&lt;link rel="stylesheet" href="&lt;?=auto_version('/css/base.css')?&gt;" type="text/css" /&gt;
  </code></pre>
  
  <p>by something like this...</p>
  
  <pre><code>&lt;link rel="stylesheet" href="&lt;?='http://cdn.externaldomain.com' . auto_version('/css/base.css')?&gt;" type="text/css" /&gt;
  </code></pre>
  
  <p>But wrapping the function around the internal URL and adding the CDN domain doesn't seem to work...</p>