title: Nginx caching with variable param order
body: <p>I am generating a cache key with nginx based on the request URI and query params that checks memcache directly and then serves the page from PHP-FPM if a cache key is not found. My problem is that many URLs have query string options that come in in varying orders and thus generated two or more separate cache keys per response.</p>
  
  <p>My cache setting is something like:</p>
  
  <pre><code>set $cache_key  "$uri?$args";
  </code></pre>
  
  <p>So URLs that come in like these with query string params in different orders end up generating multiple possible cache keys for the same type:</p>
  
  <pre><code>http://example.com/api/2.2/events.json?id=53&amp;type=wedding&amp;sort=title&amp;limit=10
  http://example.com/api/2.2/events.json?id=53&amp;limit=10&amp;type=wedding&amp;sort=title
  http://example.com/api/2.2/events.json?id=53&amp;limit=10&amp;sort=title&amp;type=wedding
  </code></pre>
  
  <p>Ad nauseum for n! possibilities...</p>
  
  <p>The end result is that memcache often fills up a lot faster than it should because I have a potential n!-1 duplicate copies of cached content simply because the query string parameters come in a different order. Is there a way I can order them alphabetically before setting the cache key to avoid this? Are there other ways to elegantly solve this issue?</p>