Dopicsi
Dopicsi

Reputation: 33

htaccess FilesMatch regex with version

Need regex help in htaccess. I need to catch css and js file with version number before extension.

Files with 0 version has no cache.

Filename example: example.0.js example.0.css

Files with larger than 0 version has 1 year cache.

Filename example: example.1.js example.9999.css

<FilesMatch "\.(css|js)$">
   ExpiresActive On
   ExpiresDefault "access plus 1 year"
   Header append Cache-Control "public"
</FilesMatch>

This work for all js and css, but I need different cache for files *.0.js and *.0.css

Upvotes: 1

Views: 561

Answers (1)

anubhava
anubhava

Reputation: 784898

You can use another FilesMatch that ends with .0.css or .0.js with no-cache headers. Also change existing regex to disallow .0.(js|css):

ExpiresActive On

<FilesMatch "(?<!\.0)\.(css|js)$">
   ExpiresDefault "access plus 1 year"
   Header append Cache-Control "public"
</FilesMatch>

<FilesMatch "\.0\.(css|js)$">
   ExpiresDefault A0
   Header set Cache-Control "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform"
   Header set Pragma "no-cache"
</FilesMatch>

Based on your comments below here is a Apache 2.4 solution to enable caching for only [0-9]+.(css|js) excluding 0.:

<If "'%{THE_REQUEST}' =~ /\.[0-9]+\.(css|js)/">
   ExpiresActive On
   ExpiresDefault "access plus 1 year"
   Header set Cache-Control "public"
</If>
<If "'%{THE_REQUEST}' =~ /\.0\.(css|js)/">
   ExpiresDefault A0
   Header set Cache-Control "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform"
   Header set Pragma "no-cache"
</If>

RewriteEngine On
RewriteRule ^(.+)\.\d+\.(css|js)$ /$1.$2 [L,NC]

Upvotes: 1

Related Questions