嗨,我希望用户能够从我的服务器(Windows)下载配置了Nginx PHP的PDF文件.这是我的Nginx.conf(服务器块)
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.PHP;
}
location /download {
internal;
alias /protected;
}
}
}
$file = '/download/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($file)) );
header('Content-Disposition: attachment; filename='.$filename.'');
header('Content-Transfer-Encoding: binary');
header('X-Accel-Redirect: '. $file);
download.PHP?id=a2a9ca5bd4a84294b421fdd9ef5e438ded7fcb09
我从这里尝试了一些示例/解决方案,但到目前为止还没有工作.文件很大(每个250到400 MB),每个用户可以下载4个文件.
最佳答案
好的 – 这里有几个问题:
原文链接:https://www.f2er.com/nginx/434366.html1)根据Nginx开发人员的说法,在一个位置内部设置根是BAD IDEA.
2)用于告知Nginx这是内部重定向的内部URL不应向用户公开.
3)我无法看到你的download.PHP文件的来源,所以我更改了你的根位置块以使用try_files,因此对该文件而不是index.PHP的/download.PHP请求.
您的项目应该如下:
project\
html - this is the root of your website
protected - this directory is not accessible directly
你的Nginx conf应该是这样的:
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;
}
}
}
不要重复使用相同的名称来表示不同的东西,这是一个好主意,因为它很混乱.我已经更改了它们,现在受保护只是指实际的物理目录,它包含您要提供的文件. protected_files只是一个字符串,允许Nginx匹配来自x-accel头的请求.
在PHP代码中唯一需要更改的是使用正确的字符串来允许Nginx获取内部位置:
$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);