Good - there are a few problems here:
1) The root root inside the location of the BAD IDEA according to the nginx developers.
2) The internal URL used to tell Nginx that it is an internal redirect should not be exposed to users.
3) I canโt see where your download.php file is located, so I changed your root location block to use try_files, so the request for /download.php will be served by this file, not index.php.
Your project should be laid out as:
project\ html - this is the root of your website protected - this directory is not accessible directly
And your Nginx conf should look like this:
http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; root /path/to/project/html; location / { try_files $uri /index.php?$args; } location /protected_files { internal; alias /path/to/project/protected; } } }
It is a good idea not to repeat the use of the same names in order to keep in mind different things, as this is quite confusing. I changed them, so now protected just refers to the actual physical directory in which the files you want to serve are stored. protected_files is just a string that allows Nginx to match the request from the x-accel header.
The only thing you need to change in your PHP code is to use the correct line so that Nginx can pick up the internal location:
$aliasedFile = '/download/real-pdf-file.pdf'; //this is the nginx alias of the file path $realFile = '/path/to/project/protected/real-pdf-file.pdf'; //this is the physical file path $filename = 'user-pdf-file.pdf'; //this is the file name user will get header('Cache-Control: public, must-revalidate'); header('Pragma: no-cache'); header('Content-Type: application\pdf'); header('Content-Length: ' .(string)(filesize($realFile)) ); header('Content-Disposition: attachment; filename='.$filename.''); header('Content-Transfer-Encoding: binary'); header('X-Accel-Redirect: '. $aliasedFile); exit(0);
source share