Htaccess - conditional rewriting and expiration

Hey there!

I have a folder /staticon the Apache 2.x web server. If the request matches

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

eg

/static/bg.jpg/1335455634

I want two things:

  • url should be rewritten to /static/bg.jpg(getting rid of timestamps)
  • it will never expire (expires 2030, max-age = 290304000, shared cache, ...)

If the request does not match, the request and its headers should be as usual, not rewrite. Ideally, any request from outside / static / * should not be affected (although "matching trailing times" should be rare ...)

I have nothing but problems with FilesMatch / RewriteCond, so I prefer not to send my bad attempts ... (Rewrite in genereal is enabled on my machine and I really have the right to send cached headers)

Dankeschön!

+5
source share
2 answers

How about something like that?

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>
+2
source
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 chose iccess plus 1 yearsfor never-expires because I found this on the Internet:

"To mark the response as" never expires, "the origin server sends. Expires about one year from the time it was sent. HTTP / 1.1 servers MUST NOT send expiration dates for more than one year in the future."

From HTTP 1.1 RFC

+4
source

All Articles