G
G
Galdar Turin2019-07-11 14:28:36
PHP
Galdar Turin, 2019-07-11 14:28:36

How to download a file using NGINX?

Please help me figure it out, I need to force the file to be downloaded when I click on it, I can’t understand how downloading via NGINX works.

...
    case '5':
            $c = mysqli_fetch_assoc(connectTables("ЗАПРОС"));
            $file = mysqli_fetch_assoc(connectTables("ЗАПРОС"));

            header("X-Accel-Redirect: /access_files/".$file["img"]);
        break;
...

location /downloads/ {
      rewrite ^/downloads/(.*) /down.php?file_name=$1 break;
      fastcgi_pass   unix:/tmp/fastcgi_socket;
      fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
      include        fastcgi_params;
    }
    location /access_files {
        alias /var/www/chat.sms-agent/chatImages;
        add_header Content-type application/octet-stream;
        internal;
    }


sim3x describe the task in the question.
The task is to launch a PHP file with the necessary data when clicking on the file AJAX, after that the PHP file checks and sends the file to the download via a fake link to the user.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Galdar Turin, 2019-07-12
@Galdar

ANSWER TO THE QUESTION

config.nginx
rewrite ^/f/(.*)/(.*)$ /downloadFile.php?id=$1&file=$2 last;

    location /file/ {
      internal;
      root /var/www/domain/c;
    }

AJAX
/* ваш скрипт функция которая будет генерировать или как то там вставлять ссылки на ваши файлы */
$('#c').append('<p id="" class="from-me downloadFile"><a href="/f/'+id+'/'+idImage+'" class="download" download><img src="'+url+'" class="downloadImage"/></a><i class="fas fa-file-download"></i><span class="size">'+size+'</span></p>');

the php itself to which the request is made
// все проверки по которым будет подставляться нужный файл
...
header('Content-Length: '.$filesize);
header('Content-Type: '.$type); // Тип файла по его расширению
header('Content-Disposition: attachment; filename='.$filename); // Имя файла
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('X-Accel-Limit-Rate: 1024000'); // Ограничение скорости скачивания
header('X-Accel-Buffering: yes');
header('X-Accel-Charset: utf-8');
header('X-Accel-Redirect: '.$files); // Путь к папке для правил редиректа nginx

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question