title: How to configure nginx to try_files first, if not exists follow the request_uri
body: <p>We have page caches with id partitioning and subdomain. Say for requests like <code>ny.site.com/cat/12345</code> or <code>la.site.com/dog/234</code>, nginx need to</p>
  
  <ol>
  <li>check if file <code>/cat/ny/1234/5.html</code> exists, return it</li>
  <li>otherwise, just use the original <code>request_uri</code> to hit the app server, and the cache file will be created</li>
  </ol>
  
  <p>We managed to figure out the subdomain and id partitioning part, but didn't get any luck on the try_files part. Always get indefinite loop errors like <code>rewrite or internal redirection cycle while internally redirecting to</code></p>
  
  <p>our nginx.conf file is like</p>
  
  <pre><code>rewrite "/cat/([0-9]{4})([0-9]{1,4})" /system/cache/cat/$subdomain/$1/$2.html break;
  rewrite "/cat/([0-9]{1,4})" /system/cache/cat/$subdomain/$1.html break;
  try_files $uri $request_uri;
  </code></pre>
  
  <p>Any hints? Thanks!</p>
  
  <p><strong>UPDATE:</strong>
  I tried the following. Nginx was looking for $request_uri (e.g., /cat/12345) in the file system instead of hitting the app server. Any thoughts?</p>
  
  <pre><code>try_files $uri @old;
  location @old {
      rewrite ^ $request_uri break;
  }
  </code></pre>