Use NGINX to Use Query Strings While Caching

Nginx has very sophisticated caching features, and with a few lines you can start optimizing it to the fullest.

First thing you’ll need to do in your config, outside of your server block is set up the cache file. The one I use on my projects is:

fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=SET_YOUR_KEY_HERE:100m inactive=60m;

You can change SET_YOUR_KEY_HERE to whatever you would like. The important piece of information here is the key_zone 100m is the size of the cache, 100 MB which should be large enough to handle a site with a few thousand unique pages.

In your server code block, you’re going to set a few variables. Most nginx setups should allow you to grab the query string parameter values without any issues, what you will want to do is create a string out of it that can be used for a key, for example I am going to set a few variables:

set $mute "{$arg\_mute}\_";
set $style "{$arg\_style}\_";
set $utmsource "{$arg\_utm_source}\_";

So what we did here was we set the $mute, $style and $utmsource variables to have the value and an underscore saved as a string. So if we set &mute=1 in our URL, the $mute value would be “1_”, if we set & the $utmsource value would be “dougcode.com_“

Then in your location block where you could talk to a FastCGI process, you would set the following:

fastcgi_cache_key "$scheme$request_method$host$uri$mute$style$utmsource";
fastcgi_cache SET_YOUR_KEY_HERE;
fastcgi_cache_valid 200 404 15m;

What that does is sets your cache key, by using $uri you are stripping the query strings from the request, and then you are just appending the values you want to that cache.

Then you are just telling it where to save your cache, and how the TTL for your cache (15 minutes for 200 and 404 response codes)

This is useful because if you are sending traffic that you need to track with analytics but they append random query strings to the end of the URL, a cache isn’t going to be useful if you don’t have it stripping the query strings off, but your application may also need to respond to certain query string parameters such as &mute=, &style= and &utm_source=. This gives you the best of both worlds, the application only receives the data it needs, nginx will cache the content which will speed up response times, and you don’t have to sacrafice tracking critical information being passed to your URL’s!

Last Updated: 2015-01-06 00:00:00 +0000 UTC

What are your thoughts on this?


RSS feed

Follow Doug On Social