June 28, 2017

Auto version your JavaScript or Stylesheet files using .htaccess

Usually, developers can maintain the cache they maintain themselves at the backend but cannot control the cache held by the browser as freely as they want unless there is proper version control. Here is a quick drop in solution in `.htaccess` file until you have proper versioning.

Most of the applications have one or many layers of cache for their system. The cache that application developer can maintain is at the backend (the server) level. However, you cannot control the cache held by the browser as freely as you want unless you version the files as well.

Versioning the files is definitely the best way to solve this problem because it is a very efficient solution which guarantees that browser will fetch the new resource when you want it to. But there are cases where this is not an easy step to be taken, for example, in a legacy app which resources are included in line the page.

So, is there a quick way to fix the problem until you go to proper versioning?

Yes! there is.

Using .htaccess we can auto version the files and force the browser to fetch files down to every second if we need to.

Here is how:

We can use server variables such as TIME_YEAR, TIME_MONTH to create an automatic version of your resource. These are variables that the web server provide to be used where suitable. And now, let’s see how to do this.

RewriteCond %{QUERY_STRING} !(v=(.<em>))
Rewriterule ^(js|scripts|css|styles)(.</em>)$ /$1$2?v=%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}%{TIME_HOUR} [r=302,nc]`

Open your .htaccess files and paste those two lines in. What these are doing is:

  • If a request comes to the server that starts with js, scripts, css or styles then rewrite the request by appending an auto-created version at the end.
  • IF a request comes with the version already in the request then don’t do anything because we don’t want it to keep rewriting the request.

Simple as that. So for example: if the request comes to https://abc.com/js/main.js it gets served as https://abc.com/js/main.js?v=2017062811. Same goes for any request coming to other paths as well. This example ensures that browser will fetch the resource again every hour. But if you add variables like TIME_MINUTE or TIME_SECOND or TIME browser will keep fetching the content more frequently.

To see what other server variables can be used visit https://httpd.apache.org/docs/trunk/expr.html#vars

