nginx X-Accel-Redirect gotcha

In one of my Rails apps, I was trying to serve up a (potentially large) file by leveraging the X-Accel-Redirect response header for nginx (instead of serving the file up directly from Rails). The idea is that you provide a guid for a file and my Rails app figures out which file you want and tells nginx where it can find it. The directory where the files are stored is not directly available via nginx; it uses an “internal” location like this in nginx.conf which points to the literal location /var/where_i_put_stuff/files_you_cant_see:


location /files_you_cant_see {
root /var/where_i_put_stuff;
internal;
}

Everything was working fine during my informal testing. But when I tested it through the application, it would immediately run up to the file download limit and error out. Sure enough, the logs showed that Rails was asked five times to download the file, even though I really only asked once. What’s up?

It turned out to be really simple. The path I was telling nginx to download from didn’t match the path I had configured in nginx.conf. (In the above example, it was as if I had set the value of X-Accel-Redirect to something like /files_i_cant_see/file_to_download.txt) Once I got those paths in sync, everything fell into place and started working great. Interesting behavior, though, to have a missing file essentially fire off an infinite loop!

This was with nginx version 0.5.25.