Using mod_rewrite to serve new version of cached resource

You should use following best practice when setting Cache-Control/Expires header for your resource

  1. The dynamic HTML should never be cache

  2. The static resource such as images/ JavaScript and CSS should be cached for ever

The question would be what if say my JavaScript is cached and i realized that there is a bug and i want to roll out a new version of JavaScript, in that case you should change the reference to JavaScript file in your HTML.
<script src="/resource/test.js">

Should be changed to

<script src="/resource/test-v1.js">

Important Note: Basic idea is you should somehow change the URL of the resource in your HTML and that will force browser to make a new request for the resource.

One way of doing that is changing the name of the file but sometimes its not possible to upload new version of JavaScript with different name on your HTTP server in that case you have one other option, you can update the test.js at same location but change URL to it in your HTML and let HttpServer rewrite the URL to same location

<script src="/resource/test.js">

You have a new version of test.js at same location and you want to force browser to download new version in that case change reference to test.js in HTML like this

<script src="/resource/v1/test.js">

Browser will make a new request to the HTTP server and on the HTTP server you can create a URL rewrite rule like this

RewriteEngine on
RewriteLogLevel 3
RewriteLog "/tmp/rewrite.log"

RewriteRule /resource/v([0-9]+)/(.*) /$2

What this rule will do is it will take the incoming request /resource/v1/test.js and rewrite it to /resource/test.js and which will return a new copy of the test.js to browser

No comments: