Nginx proxy cache 301 redirects but ignore querystring

301-redirectnginxPROXYreverse-proxy

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?

Best Answer

I'm afraid there is no way to do what you want. The problem is that your backend hands out the 301 response with the query parameter, and nginx has no methods to modify the HTTP response that is saved to the cache.

Your only option is to use the aid as additional cache key.