Nginx Cache Busting Rewrite Rule

Following on from an excellent guide on cache busting, we see how you can accomplish this in nginx

We wanted to add cache busting to the football tipster site I’m involved with because frankly we were doing too good a job at making the browser cache stuff in between visits.

We followed the CSS Tricks guide to Cache Busting and were able to easily incorporate the changes into some .htaccess rules that are powering the site. Perfect.

Our dev environment uses wp-vagrant which uses Nginx over Apache. This meant when we added the cache busting filenames some of our assets stopped loading.

Luckily we were able to rewrite the .htaccess rule as an Nginx one.

Snippet of Original Rule;

RewriteRule ^(.+)_(\d+)\.(js|css|png|jpg|gif)$ $1.$3 [L]

This rule lived within a mod_rewrite block and would need to be preceded by the standard incantations to get rewriting working

Rewritten Nginx Rule;

location / {
  rewrite ^/(.+)\.(\d+)\.(js|css|png|jpg|gif)$ /$1.$3 break;
}

The rewrite is incredibly similar, we replace [L] for its Nginx equivalent break.

Hope that helps!

Recent posts View all

Web DevProductivity

Keeping on top of website updates

Learn what website updates are, what they entail, why they are important, and how we can help

Freelancing

Getting the most out of your agency

Here are some tips based on years of working with, for, and as an agency on how to get the most out of any work you do.