Nginx – Rails – Nginx not caching images

nginxruby-on-railsunicorn

I've got a VPS where I'm running my Rails app using Nginx and Unicorn. I was successful to add expires headers to JS and CSS files, however I cannot force Nginx to cache images as well (according to YSlow and Google PageSpeed Insights).

Here's my server block:

server {
  listen   80;
  root /home/rails/public;
  server_name _;
  index index.htm index.html;

  location / {
    try_files $uri/index.html $uri.html $uri @app;
  }

  location ~* ^.+\.(jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|mp3|flv|mpeg|avi)$ {
    try_files $uri @app;
  }

  location @app {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://app_server;
  }

  location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
    expires max;
  }

}

The last piece of code is how I have acheived chaching of CSS and JS, but it is not working for images. What am I doing wrong? Should I do some additional changes elsewhere?

Thanks a lot!

Best Answer

You have two location blocks matching images :

location ~* ^.+\.(jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|mp3|flv|mpeg|avi)$ {
    try_files $uri @app;
}

And

location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
    expires max;
}

Nginx will stop at the first matching regex location block so the second location block is never used for jpg, jpeg, png, gif and ico files.

Update : details for the fallback caching

server {
  listen   80;
  root /home/rails/public;
  server_name _;
  index index.htm index.html;

  location / {
    try_files $uri/index.html $uri.html $uri @app;
  }

  location ~* ^.+\.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires max;
    try_files $uri @app;
  }

  location ~* ^.+\.(zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|mp3|flv|mpeg|avi)$ {
    try_files $uri @app;
  }

  location @app {
    if ($uri ~* ^.+\.(jpg|jpeg|png|gif|ico|css|js)$) {
        expires max;
    }
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://app_server;
  }

}