-->

Set fastcgi_cache_key using original $request_uri

2019-02-26 23:27发布

问题:

I am trying to integrate a WordPress plugin (Jetpack's Related Posts module) which adds query strings to the end of post URLs. I would like to cache URLs with FastCGI while completely ignoring the query strings/$args.

My current config is: fastcgi_cache_key "$scheme$request_method$host$request_uri";

I am aware of using the solution mentioned here to turn my $skip_cache variable off for URLs containing a certain $arg, which works. However, I want to cache the same result regardless of the value of the $args rather than using a unique cache key for each set of $args.

I am also aware of some suggestions to just use $uri in the fastcgi_cache_key rather than $request_uri; however, because $uri is not just the original requested URI minus the $args, something in the WordPress architecture (likely pretty links) forces all requested URIs to return the same cache result (rather than a different result for each page).

Is there any way to truly use the originally requested URI without including the $args in the cache key?

回答1:

Just now, I had similar problem. So, my solution:

In the nginx config add to the

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

Then you will have a variable $request_path, which contains $request_uri without query_string.

So use $request_path for cache key

fastcgi_cache_key "$scheme$request_method$host$request_path"

Important. The "map" directive can be added only to "http {}". This directive will be execute for all requests for all hosts.