Nginx try_files absolute path

nginx

I'm new at nginx, what I'd like to do is catch all image requests (*.jpg|png|gif) and forward them to a php script outside the scope of root.

My current, kinda working script is this:

server {

   index index.php;

   # PHP-FPM
   location ~ \.php$ {
      include snippets/fastcgi-php.conf;
      fastcgi_pass unix:/var/run/php5-fpm.sock;
   }

   # Images handler
   root /var/www/images-handler;
   location ~* \.(gif|jpg|png) {
      rewrite ^ /img.php last;
   }

}

The problem is that I have to change the root variable to /var/www/website-contents. Since website-contents and images-handler don't have the same parent directory, I add a root variable to my location segment like so:

root /var/www/website-contents;

location ~* \.(gif|jpg|png) {
   root /var/www/images-handler;
   rewrite ^ /img.php last;
}

But it doesn't work. All the images return a 404 response.

Do I have to make /var/www the root, and add website-contents and images-handler in their own location segments, / and ~* \.(gif|jpg|png) respectively? Should I make a symbolic link for /var/www/images-handler inside /var/www/website-contents?

Is there a better solution to all of this?

Thanks a lot.

Best Answer

Currently, all php scripts are executed by your location ~ \.php$ block, with the root you provided. If you want to execute a php script with a different root, you need to override that location. There are a number of ways to achieve this. Just for one php script, a location = would be simplest. For example:

root /var/www/website-contents;

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
}

location ~* \.(gif|jpg|png) {
    rewrite ^ /img.php last;
}

location = /img.php {
    root /var/www/images-handler;
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
}