Skip to content

Instantly share code, notes, and snippets.

@jpolete
Last active January 4, 2016 04:28
Show Gist options
  • Save jpolete/8568285 to your computer and use it in GitHub Desktop.
Save jpolete/8568285 to your computer and use it in GitHub Desktop.
A simple (albeit limited) setup for caching static assets in WordPress. Sets far future http headers and then writes urls with timestamps. Full explanation at http://blog.poleteweb.com/2013/09/26/performance-tuning-wordpress-far-future-headers-and-cache-busting/
function cache_buster_url($uri) {
//Get base url of WP installation
$base_url = get_bloginfo('url');
//Get local path to the root of the WP installation
$installation_root = $_SERVER['DOCUMENT_ROOT'];
//Get path (from root) to file
$path_info = str_replace($base_url, '', $uri);
//If path has no dot (no file extension), return unchanged
if(strpos($path_info, ".") === false) { return $path_info; }
//Get full local path to file
$local_path = $installation_root . $path_info;
//Generate numeric timestamp based on modification date
$cache_buster_date = date("YmdHis", filemtime( $local_path ));
//Add the timestamp to the file name, right before the file extension
$url_chunks = explode(".", $path_info);
array_splice($url_chunks, count($url_chunks) - 1, 0, $cache_buster_date);
//Return full, rewritten uri
return $base_url . join(".", $url_chunks);
}
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Strip timestamp (cache buster) from filename
RewriteRule ^(.+)\.(\d+)\.(js|css|png|jpg|gif)$ $1.$3 [L]
# Wordpress Pretty URLs
RewriteRule . /index.php [L]
</IfModule>
# Far Future Expires Header
# http://www.particletree.com/notebook/automatically-version-your-css-and-javascript-files/
# http://httpd.apache.org/docs/2.4/mod/mod_expires.html
<IfModule mod_expires.c>
ExpiresActive on
ExpiresByType application/javascript "access plus 6 months"
ExpiresByType image/jpg "access plus 6 months"
ExpiresByType image/jpeg "access plus 6 months"
ExpiresByType image/gif "access plus 6 months"
ExpiresByType image/png "access plus 6 months"
ExpiresByType text/css "access plus 6 months"
</IfModule>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment