Nginx proxy cache 301 redirects but ignore querystring

dlrust asked:

We have a lot of ad-based traffic that pass various query string params on the URL, but these do not affect the content/output of the pages.

I currently have the following nginx proxy cache configuration, which passes uncached requests to another backend server that actually returns the content.

proxy_cache_key    "$request_method@$scheme://$host:$server_port$uri";
proxy_cache_valid  200 15m;
proxy_pass         http://backend;

I am just using the $uri and not the $args within the cache key so that both of the following would pull from the same cache, which is working great

http://www.somedomain.com/?aid=129f58ad4af8f9de08bbd6bb7df22850
http://www.somedomain.com/?aid=4db00563d4181dc8d1dfd3b5cd6dc708

But, if I start caching the 301 redirect responses from the backend server

proxy_cache_valid  301 15m;

Then we start caching the 301’s returned from the backend server, using the non-arg cache key which causes a problem because:

    the first request to

http://somedomain.com/?aid=129f58ad4af8f9de08bbd6bb7df22850
redirects to...
http://www.somedomain.com/?aid=129f58ad4af8f9de08bbd6bb7df22850

but
http://somedomain.com/ or http://somedomain.com/?foo=bar
pulls from the cache and redirects to...
http://www.somedomain.com/?aid=129f58ad4af8f9de08bbd6bb7df22850

Is there a way to have the 301 redirects cached that ignore the querystring and just passthrough whatever querystring params are present on the request?

My answer:


Based on the semantics of what these URLs do, I think it would be best if nginx did not attempt to cache these requests at all; rather, to always pass them up to your application, so that you can do the appropriate tracking.

Fortunately this is a one-liner:

proxy_no_cache $arg_aid;

will bypass the nginx cache and pass the request up to your app if the aid argument is present in the query string.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.