How to configure nginx to try_files first, if not exists follow the request_uri

11,602

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).
Share:
11,602
QWJ QWJ
Author by

QWJ QWJ

Updated on June 04, 2022

Comments

  • QWJ QWJ
    QWJ QWJ almost 2 years

    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;
    }
    
  • QWJ QWJ
    QWJ QWJ over 10 years
    thanks for the input, but I don't get it. How would this try_files solve the problem? i.e., when $uri doesn't exist on disk, go back to the original $request_uri?
  • Mohammad AbuShady
    Mohammad AbuShady over 10 years
    try_files tells nginx what to try for that request, so i'm simply telling it to see if the $uri has an html file for it, otherwise try $uri, If you have a php file that handles the requests then u should pass that as a 3rd parameter ie: /index.php$request_uri for example
  • Poonam Bhatt
    Poonam Bhatt about 10 years
    @surajs21: I have url like www.test.com/public/ and www.test.com/public/web and www.test.com/public/web1. this is ZF2 I am facing issue like it properly get link to first URL 'public/' but issue with www.test.com/public/web and www.test.com/public/web1. ngin x not able to map it. Please help me stackoverflow.com/questions/21377321/…