0

With Nginx, I want to add .php files at will to my document root and have them just work without the extension. Not only that, but I want these random .php files to also take a path_info after them.

So, if I add a file /path/to/root/apple.php I want www.example.com/apple to work, as well as www.example.com/apple/123 or www.example.com/apple/123/something or www.example.com/apple/123/something/something.

I want to be able to add files like this all of the time, all over the place, without having to add explicit Location blocks for each of them in the Nginx configuration. I want to go on to add /path/to/root/orange.php and /path/to/root/quince.php and anything else, and I want those paths to immediately work, without their .php extension, and with any arbitrary path_info.

In Apache, I can just do Options MultiViews. In Nginx, maybe this is not yet possible, but if so, I would just want to know that, so I can just stop trying to figure it out.

Andrew Banks
  • 301
  • 1
  • 3
  • 6

1 Answers1

1

A common pattern is to look for the static file and if not found perform some default action. That default action might be to extract the first element of the URI and turn it into a .php. I do make one assumption, and that is with www.example.com/apple/123/something/something, the PHP file is always the first element of the path, in this case apple.php.

root /path/to/root;

location / {
    try_files $uri $uri/ @php;
}

location ~ \.php$ {
    try_files $uri =404;
    ...
}

location @php {
    rewrite ^/([^/]+)(/|$) /$1.php last;
}

I haven't addressed the path info issue. There are a number of ways that PHP scripts can access the path info. Some will look at the original REQUEST_URI, in which case you need to do nothing more than the above.

Richard Smith
  • 45,711
  • 6
  • 82
  • 81
  • Thank you. Yes, I was thinking something like that. When I do path_info, I almost always make it just one segment long. Like /widgets(.php)/123, not /widgets(.php)/something/123. If I needed that, I would do /widgets/something(.php)/123. The folder and file names roughly correspond to a database schema, and the path_info is a look-up key a particular row, roughly. So maybe a Location block to try $uri.php and another with a rewrite expression to try /path/to/some.php/with_one_segment_of_path_info. – Andrew Banks May 15 '16 at 14:03
  • Obviously the rewrite could be crafted to place the `.php` just before the last `/`, but that would mean that `www.example.com/apple` becomes a special case. – Richard Smith May 15 '16 at 14:06