Search code examples
apache.htaccessurl-rewritingcache-controlmod-expires

htaccess - conditional rewrite and expire


Hey there!

I have a folder /static in my Apache 2.x server webroot. If a request matches

/static/<somename like [\S-_]+>.(png|jpg|css|js)/\d{8,15}

for example

/static/bg.jpg/1335455634

I want two things:

  • url shall be rewritten to /static/bg.jpg (getting rid of the timestamp)
  • it shall become a never-expire ('expires 2030, max-age=290304000, public cache, ...)

If the request does not match, the request and it's headers should be as normal, no rewrite. Ideally, any request outside /static/* should not be affected (though «coincidental trailing timetamps» should be rare...)

I have nothing but trouble with FilesMatch / RewriteCond, so I rather not post my poor attempts... (Rewrite in genereal is enabled on my machine, and I do possess the rights to send cache-related headers)

Dankeschön!


Solution

  • How about something like this?

    RewriteEngine on
    RewriteRule ^static/([^/]+\.(png|jpg|css|js))x?/\d{8,15}$ /static/$1 [NC,L]
    
    <FilesMatch "\.(png|jpg|css|js)$">
        <IfModule mod_expires.c>
            ExpiresActive On
        </IfModule>
        <IfModule mod_headers.c>
            ExpiresDefault "access plus 10 years"
        </IfModule>
    </FilesMatch>