Search code examples
ruby-on-railsnginxunicorn

Nginx fall-through urls with caching


I have Rails app that has routes matching static files that are generated on first access.

Everything works fine if I have this block commented out in my site.conf:

 location ^~ /uploads/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

Is there a way to have best of both worlds and have location block to be only activated if the actual file exists and fall-through if it isn't? Maybe add try inside?


Solution

  • One of best practices to serve response based on logic "local disk static file vs. dynamic response with backend" is try_files:

    location ^~ /uploads/ {
      gzip_static on;
      expires max;
      add_header Cache-Control public;
      try_files $uri @backend;
    }
    
    location @backend {
      proxy_pass ...
    }
    

    See official docs here.