Question

We have page caches with id partitioning and subdomain. Say for requests like ny.site.com/cat/12345 or la.site.com/dog/234, nginx need to

  1. check if file /cat/ny/1234/5.html exists, return it
  2. otherwise, just use the original request_uri to hit the app server, and the cache file will be created

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 rewrite or internal redirection cycle while internally redirecting to

our nginx.conf file is like

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;

Any hints? Thanks!

UPDATE: 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?

try_files $uri @old;
location @old {
    rewrite ^ $request_uri break;
}
Was it helpful?

Solution

Try with this

location ^~ ^/cat/([0-9]{4})([0-9]{1,4}) {

    try_files "/cat/ny/$1/$2.html" @app_server;

}
location @app_server{

    # pass this to your app server for processing.

}
  1. Use ^~ as this will also include the edge case like /cat/12345/ (ending slash).
  2. And just be sure whether you want $uri (which is without query string) or $request_uri ( which contains query string).

OTHER TIPS

I never tried this my self before but this is how I would write it

location / { # or whatever location you see fit to your requirements
    try_files $uri.html $uri;
    # I don't know if the `.` needs to be escaped `$uri\.html`, you can try both
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top