Duplicated Folder Names, Nginx, and the difference between Alias and Root

While this is something quite simple, I have run into this a lot online. The solution is actually quite simple, so I thought I’d point it out.

The problem: someone wants to serve a subdirectory. As a result, he sets up something like this:


location /download/ {
root /home/example.com/download/
}

He restarts Nginx. No problems. Unfortunately, when he tries to get something from the directory (http://example.com/download/file.zip for example), he can’t download it! Worse yet, when he looks at the error log, the result is puzzling.

open() "/home/example.com/download/download/files.zip" failed (2: No such file or directory)

WTF? Why is download duplicated in there?

Some people I’ve seenhave advocated the boneheaded idea of moving the file to the subdirectory and living with it, or even worse, setting the root to /home/example.com. The actual answer is to use the alias keyword in the config file.


location /download/ {
alias /home/example.com/download/
}

As you can guess, root doesn’t affect anything in the URI you pass. It uses /home/example.com/download as the ROOT for the website, and then appends the second “/download/” afterwards. Alias strips off the /download/, leaving you with the remaining file path you needed to get the file.

If you have had this problem, read the Nginx docs! They aren’t too hard. (God knows, I should be reading them more.)