.htaccess

htaccess rewrite for cache busting


In an attempt to cache bust .css and .js files, and not wanting to go the query string route, I want to, via htaccess rewrite paths that start with "foo*/" to remove/ignore "foo*/" - the asterisk can be any number, as it will be the version.

example #1:

/foo123/css/style.css
should actually just request:
/css/style.css

example #2:

/foo456/js/script.js
should actually request:
/js/script.js

Another way could be to have the version number, to be ignored, in the file name. again, the number can be anything, so it cant be hardcoded, so perhaps it should explode file name, and remove 2nd part. example:

/css/styles.123.css
should actually just request:
/css/styles.css

or:

/js/script.11235.js
should actually just request:
/js/script.js

So far what i got, which is not working at all, is this, which just gives me a 404:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)\.(\d+)\.(css|js)$ $1.$3 [L]

above code is from: https://github.com/h5bp/server-configs-apache/blob/02a601e5914a504e019c46b76bb21adab89cb686/src/.htaccess#L677-692

I currently have this, for pretty urls, so it need to keep in consideration not to break/interfere with this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

grateful for any help, thanks!


Solution

  • add this for versioned paths:

    RewriteCond %{REQUEST_URI} ^/foo\d+/(.*)$
    RewriteRule ^ /%1 [L]
    

    replace with this for versioned filenames:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)\.\d+\.(css|js)$ $1.$2 [L]
    

    leave your pretty url entries intact

    note: dont forget there will only be one RewriteEngine On in .htaccess