Skip to content

Instantly share code, notes, and snippets.

@reinink
Last active January 1, 2021 16:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save reinink/46771954850fbe0c196f to your computer and use it in GitHub Desktop.
Save reinink/46771954850fbe0c196f to your computer and use it in GitHub Desktop.
Add filename-based cache busting to Laravel
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)\.(\d+)\.(css|gif|jpeg|jpg|js|png|svg)$ $1.$3 [L]
</IfModule>
<?php
// Add the the following code right before the last line of the existing
// Laravel "server.php" file, which will look something like this:
// `require_once $paths['public'].'/index.php';`
if (preg_match('/^(.+)\.(\d+)\.(css|gif|jpeg|jpg|js|png|svg)$/', $uri, $matches))
{
$requested = $paths['public'].$matches[1].'.'.$matches[3];
if (file_exists($requested))
{
$types = array(
'css' => 'text/css',
'gif' => 'image/gif',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'js' => 'application/javascript',
'png' => 'image/png',
'svg' => 'image/svg+xml'
);
header('Content-type: '.$types[$matches[3]]);
readfile($requested);
exit;
}
}
<!-- Stylesheet -->
<link rel="stylesheet" href="/css/main.{{ filemtime(public_path() . '/css/main.css') }}.css">
<!-- JavaScript -->
<script src="/js/min/site-ck.{{ filemtime(public_path() . '/js/min/site-ck.js') }}.js"></script>
@molbal
Copy link

molbal commented Jan 1, 2021

Thanks Jonathan!

I had to modify server.php a bit, this is how it worked for me with Laravel 7.22.2:

if (preg_match('/^(.+)\.(\d+)\.(css|gif|jpeg|jpg|js|png|svg)$/', $uri, $matches))
{
    $requested = realpath(__DIR__."/public".$matches[1].'.'.$matches[3]);

    if (file_exists($requested))
    {
        $types = array(
            'css' => 'text/css',
            'gif' => 'image/gif',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'js' => 'application/javascript',
            'png' => 'image/png',
            'svg' => 'image/svg+xml'
        );

        header('Content-type: '.$types[$matches[3]]);
        readfile($requested);
        exit;
    }
}

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