Nginx: location, alias and try_files

webjay asked:

I have the following piece of magic in our Nginx configuration:

location /uploads {
  alias /mnt/macchina;
  location ~ ^/uploads/ {
    try_files $uri @rewrite;
  }
}

location @rewrite {
  rewrite ^/(.*)$ /index.php?q=$1;
}

It works, but doesn’t look like poetry to me, so I’m thinking there might be a simpler approach.

The goal is that for /uploads/ Nginx should see root as /mnt/macchina and try_files at $uri or goto @rewrite where it should still see root as /mnt/macchina.

Is there a better way?

My answer:


Simplifying it would require modifying the PHP web application to be a little smarter about how it determines what URL is being requested.

While most PHP web apps simply grab this information from path info, yours apparently does not, and requires the request path to be passed in a parameter q. The reason the rewrite is written this way is to strip the leading / from the path.

With a properly written PHP app that got the URL from path info, you could get rid of the rewrite entirely and just use try_files $uri /index.php;. Talk to the app developers.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.