Skip to main content
3 of 3
added 593 characters in body
Ivan Shatsky
  • 4.2k
  • 2
  • 11
  • 25

With the try_files directive fallback URI specified as /index.php$is_args$args, you are performing an internal redirect. The rewritten request processing starts from the beginning, choosing the second location to handle it.

If you don't expect any API request to be served with a static file (which is 99% of all cases), don't use all that try_files and nested location setup at all. Instead, you need to unconditionally serve any API request with the /var/www/html/api/web/index.php script. Try the following location:

location ^~ /api/ { root /var/www/html/api/web; rewrite ^/api(/.*)$ $1 break; fastcgi_pass api:9000; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root/index.php; fastcgi_param REQUEST_URI $uri$is_args$args; } 

Only if your case falls under the remaining 1% — and you can receive a request with the /api/ prefix that should be served with a static file — then you can fix your configuration the following way:

location ^~ /api/ { root /var/www/html/api/web; rewrite ^/api(/.*)$ $1 break; try_files $uri $uri/ /api/index.php$is_args$args; location ~ \.php$ { rewrite ^/api(/.*)$ $1 break; fastcgi_pass api:9000; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root/index.php; fastcgi_param REQUEST_URI $uri$is_args$args; } } 

The first correction is to add the /api prefix to the try_files fallback URI, ensuring the rewritten request is processed within the same location. The second is to strip that same prefix using the rewrite directive, making the URI without the /api prefix available via the $uri built-in nginx variable. Even when using nested locations, only a single location is selected to process the request. So if the rewritten URI becomes /api/index.php, the regular expression from the outer location will not apply, and the $1 variable will always be empty within your nested location.

Ivan Shatsky
  • 4.2k
  • 2
  • 11
  • 25