To control static file downloads, a common approach requires PHP to read the file with file_get_contents and pass it to the client.

The way to save resources is to use the X-sendFile module of Nginx

Nginx has a special resource directory that cannot be accessed directly by the client and requires PHP permission to download it.

1. Set nginx

location /request/uri/ {
    internal;
    alias /real/path/;
}Copy the code

The directory /request/uri/ is set to internal, so clients cannot access it directly.

Alias Indicates the real directory of the file. Generally, the directory is not in the public directory and cannot be accessed.

Ensure that the Settings take effect.

nginx -s reloadCopy the code

2. Access PHP

// Get the name of the file to download:$p_file = '/request/uri/filename.ext'; // tell nginx to release: header('Content-type: application/octet-stream'); / / here$fileName = basename($p_fileFilename. Ext header('Content-Disposition: attachment; filename="' . $fileName . '"');
// nginx sendfile
header('X-Accel-Redirect: '.$p_file);Copy the code

There are also control options that need to be sent ahead of x-Accel-Redirect

X-Accel-Limit-Rate: 1024 X-Accel-Buffering: yes|no X-Accel-Charset: utf-8

Documents: https://www.nginx.com/resources/w…