Nginx using X-Accel-Redirect response header to control file been download

Server Environment

1
2
3
4
5
6
7
8
$ cat /etc/issue
Ubuntu 14.04.5 LTS \n \l

$ php -v
PHP 5.6.33-1+ubuntu14.04.1+deb.sury.org+1 (cli)

$ nginx -v
nginx version: nginx/1.4.6 (Ubuntu)

This demo directory structure

1
2
3
4
5
6
7
$ tree /www/download/
/www/download/
├── index.php
└── public
└── android-x86-5.1-rc1.iso

1 directory, 2 files

Nginx website configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server {
listen 80;
server_name _;
root /www/download;

location /public {
internal;
limit_rate 200k;
alias /www/download/public;
}

location / {
index index.php;
}

location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php5.6-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}

The most important kayword is internal in code location /public which told the nginx that URL ‘http://xx/public' can not be accessed.
limit_rate limits the file download speed.

PHP Code

1
2
3
4
5
6
7
8
<?php
$dir = '/public/';
$file = "android-x86-5.1-rc1.iso";

header('Content-Type: application/octet-stream');

header("Content-Disposition: attachment; filename='$file'");
header("X-Accel-Redirect: {$dir}{$file}");
Share