Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 697
Frank Nocke Avatar asked Apr 26 '12 15:04

Frank Nocke


2 Answers

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteRule ^static/([^.]+\.(png|jpe?g|css|js))/\d{8,15}$ static/$1 [L,R,NC]

# now set expire date to today + 1 year
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresByType image/jpeg "access plus 1 years"
    ExpiresByType image/png "access plus 1 years" 
    ExpiresByType text/css "access plus 1 years"
    ExpiresByType text/js "access plus 1 years"
    ExpiresByType text/javascript "access plus 1 years"
    ExpiresByType application/javascript "access plus 1 years"
    ExpiresByType application/x-javascript "access plus 1 years" 
</IfModule>

I have chosen iccess plus 1 years for never-expires because I found this on web:

"To mark a response as "never expires," an origin server sends an Expires date approximately one year from the time the response is sent. HTTP/1.1 servers SHOULD NOT send Expires dates more than one year in the future."

From the HTTP 1.1 RFC

like image 168
anubhava Avatar answered Oct 24 '22 00:10

anubhava


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>
like image 29
jesal Avatar answered Oct 24 '22 02:10

jesal