Nginx – How to handle a url that has multiple sub-directories

stuartambient asked:

In my app, I have a route /audio/* so any number of audio folders get picked up by the route. I’m not sure how to handle it in Nginx. Basically I need to access these files a) that are stored outside of the site root and b) 4 or 5 directories deep. I can only put in 3 as the alias since the others are not known beforehand.

This is a url - - [03/Nov/2017:23:21:33 +0000] "GET /vagrant/TestRails/Music/VA%20-%20Punk%2045%20Chaos%20in%20the%20City%20of%20Angels%20and%20Devils%20(2016)/20%20The%20Hollywood%20Squares%20-%20Hollywood%20Square.mp3 HTTP/1.1" 500 595 "
2045%20Chaos%20in%20the%20City%20of%20Angels%20and%20Devils%20(2016)/20%20The%20Hollywood%20Squares%20-%20Hollywood%20Square.mp3" "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"

My site is in /vagrant/TestRails/MediaExplorer , the audio files exist in /vagrant/TestRails/Music/.../.

Edit: Posting entire server block:

server {
  listen      80;
  server_name localhost:8000;

  access_log /var/log/nginx/access.log;
  error_log  /var/log/nginx/errorlog debug;
  root       /vagrant/TestRails/MediaExplorer;
  index      /home.slim;

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    try_files /system/maintenance.html $uri $uri/home.slim $uri.html @ruby;

   location @ruby {
     proxy_pass http://media_explorer;

   # ** This is the block in question **
   location /audio/ {
     alias /vagrant/TestRails/Music/Album1.....n/files;
     try_files $uri /subfolder/$uri $uri/;
     autoindex on;

Is this something that can be done? So far it is not working obviously. I tried some try_files and while things got completely thrown off, not sure if that is method to use anyway.

My answer:

I can think of a couple of possible solutions for this.

  • Have your application sort out the actual on-disk location of the file and then return an X-Accel-Redirect to nginx to serve the actual file.
  • Use an overlay filesystem to have the files all appear in the same (virtual) directory.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.