Enable Caching Query String on Nginx FastCGI Cache

Using Nginx server-side caching, by default, a page with a query string will not be cached (BYPASS).

But, some query strings should be cached for better performance, for example:

If you use RunCloud Hub from RunCloud, you can enable cache on these query strings easily.

Go to Settings – RunCloud Hub – RunCache – Rules, and enable the “Allow Cache Query String” option.

Ignore Caching Different Query String on Nginx FastCGI Cache

The solution above is enough for most cases. But it will create a different cache for a different query string.

For example, these three links will create three different caches in the Nginx FastCGI cache.

https://youdomain/sample-page/
https://youdomain/sample-page/?utm_source=facebook
https://youdomain/sample-page/?utm_source=email

If you heavily use the query strings above, you will probably want those links to be served using a single cache from the main page (without query string) URL.

https://youdomain/sample-page/

When this post is published, this scenario is not supported by RunCloud. (I will update this post when there is a change in the future).

Fortunately, we have full control of our server in RunCloud, so we will customize it to make it happen.

First, you can create a custom Nginx config, choose the location.http type, and add this custom Nginx config.

map $request_uri $request_path {
    ~(?<captured_path>[^?]*) $captured_path;
}

Second, log in to your server as the root user using OpenSSH/Terminal (Mac) or Putty/Powershell (Windows).

ssh root@youripaddress

Change youripaddress with your server IP Address.

Third, edit one of Nginx config file, for example, I use nano to edit this file.

nano /etc/nginx-rc/extra.d/webappname.location.proxy.runcloud-hub.conf

Change webappname with current web application name in RunCloud.

Edit and replace $request_uri with $request_path on the cache key, so it will look like this.

set $cache_key "$scheme$request_method$host$request_path";

Fourth, reload Nginx to apply the latest Nginx config update.

You can run this command to test your Nginx config configuration first,

nginx-rc -t

If the test was successful, then reload Nginx using this command,

systemctl reload nginx-rc

Done! Do not forget to use the Clear All Cache feature in RunCloud Hub and check the result.