Search code examples
phpnginxhttp-redirectfpm

nginx not redirecting to upstream location


I thought I had understood the basics of nginx rewrite rules. How wrong I was.

Can you please let me know what is I am doing so wrong here:

    server {
    listen 80;
    server_name myserver;
    index index.php index.html index.htm;
    root /apps/user/websites/;

    location / {
     autoindex on;
    }
   location ~ myapp {
       try_files $uri $uri /office/myapp/api/public/index.php;
   }
   location ~\.php$ {
      try_files $uri $uri /office/fake/index.html;
#      include fastcgi.conf;
#      fastcgi_pass php-fpm-upstream;
    }
}

If I visit http://myserver/office The index.php is accessed, but instead of being caught by the last location (~.php$) as I thought it would, it is processed as a text file and send to the browser. I was expecting to receive the office/fake/index.html file instead.

Thank you very much, Andres


Solution

  • Regex matching locations are checked in the same order they are appeared in the config file. Having the

    location ~ myapp {
        try_files $uri $uri /office/myapp/api/public/index.php;
    }
    

    before the

    location ~\.php$ {
        try_files $uri $uri /office/fake/index.html;
    #    include fastcgi.conf;
    #    fastcgi_pass php-fpm-upstream;
    }
    

    would give you an endless loop on every URI containing myapp substring (except those that are matching existed files and not ended with .php) because the /office/myapp/api/public/index.php URI matches the myapp regex. You should swap those locations in order to get this configuration workable.