[HOW-TO] Fix problem with Drupal + ImageCache when use Nginx as a reverse proxy

Category:

I have set Nginx as a reverse proxy according to this tutorial -> [HOW-TO] Use Nginx as a reverse proxy for DirectAdmin which work fine. Then, I started to use Nginx to serve static files for one vhost which is running Drupal. PHP scripts still send to Apache to process through PHP-FPM. Everything seems to work fine until I found that there is one problem. The problem of images which is process by ImageCache. When I upload image, it doesn't shows as it should be. So, I googled around and found a website that explain how to do it.

Below is what I quote from what they said :

So Nginx shouldn’t try to serve static files from this directory unless they exist. Otherwise, it will generate a 404 and images will break. With this fix, we are catching the 404 generated by Nginx on static files. We are then forwarding the request to Apache (proxy_pass) so it processes it correctly. We are also caching all 404s for 1 minute to avoid slamming Apache. Be sure to “fix” all the other 404 errors so Apache does the least amount work. Most of the time, these 404 errors come from missing favicon.ico or non-manipulated images.

Then, from my setup before, I did a bit different to them. Actually, it's all the same but I comment out something. So, my vhost code will look like below :

# nano -w /usr/local/nginx/vhosts/vhostdomain1.com.conf

server {
    listen xxx.xxx.xxx.xxx:81;
    server_name vhostdomain1.com alias www.vhostdomain1.com;
    access_log  /var/log/nginx_vhostdomain1.com_access.log  main;
    error_log  /var/log/nginx_vhostdomain1.com_error.log debug;

    location / {
        proxy_pass http://xxx.xxx.xxx.xxx;
        proxy_redirect     off;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;

     }

     location @imagecache {
        proxy_pass   http://xxx.xxx.xxx.xxx;
        proxy_set_header   Host   $host;
        proxy_set_header   X-Real-IP  $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
     }

     location ~* ^.+.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js)$ {
         root   /home/admin/public_html;
         error_page    404 = @imagecache;
         proxy_cache_valid  404  1m;
     }
}

That's it. Your ImageCache should work properly with NginX Reverse Proxy after you reload your nginx config.

Tested with below software :
1. CentOS 5.4 / 5.5 - 64 bits
2. DirectAdmin 1.37 - With Custombuild 1.2
3. Apache 2.2.17 - Worker MPM
4. Nginx 0.8.5 - Run as a Reverse proxy
5. PHP 5.2.17 / 5.3.5
6. PHP-FPM in PHP 5.3.5
7. APC 3.1.7
8. Drupal 6.20

Source
- http://blog.unixy.net/2010/09/nginx-drupal-imagecache-apache-proxy_pass-404/