php – Downloading a file using X-Accel-Redirect

Question:

NGINX says not found when I try to download a file from http://site.com/download/?id=95

the /_files folder is located one level above /www , i.e.

scripts here: /site/www/

and here the files: /site/_files/

The /_files folder may contain subfolders.

Site config

server {
    listen *:80; ## listen for ipv4
    server_name site.com;
    access_log /var/log/nginx/access-site.log;
    location / {
        proxy_pass http://127.0.0.1:88/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_connect_timeout 120;
        proxy_send_timeout 120;
        proxy_read_timeout 180;
    }

    location /download/ {
       internal;
       alias /var/sites/site/_files/;
    }


    location ~* \.(jpg|jpeg|gif|png|webp|ico|css|bmp|swf|js|html|txt)$ {
        root /var/sites/site/www;
    }

}

The script that downloads the file

header("X-Accel-Redirect: /download/".$route);
header("Content-Type: application/x-force-download");
header("Content-Disposition: attachment; filename=\"".$file."\"");

As a result, the title looks like this

X-Accel-Redirect: download/content/95/arch.rar

What could be the problem?

Answer:

the problem was in trying to use the internal ( internal ) location s /download as an external (links to the appearance of the world http://site.tld/download/... ).

this location is internal according to the requirements of nginx itself for the correct operation of the X-Accel mechanism.

the problem is solved by renaming the location into some definitely unused name. For example:

location /intenal-download {
  internal;
  alias /путь/к/файлам;
}

and at the same time return the corresponding value in the X-Accel-Redirect header. based on the above example, something like this:

header("X-Accel-Redirect: /internal-download/".$route);

note that the path in the title must start with a slash.

Scroll to Top