3

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.

0

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;
}
1
  • Awesome! It works, and I finally understand what's really going on. I've spent hours trying to figure it out, thank you! – Julien Dec 10 '15 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.