使用PHP和nginx X-Accel-Redirect服务大文件

前端之家收集整理的这篇文章主要介绍了使用PHP和nginx X-Accel-Redirect服务大文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

嗨,我希望用户能够从我的服务器(Windows)下载配置了Nginx PHP的PDF文件.这是我的Nginx.conf(服务器块)

@H_301_5@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; } } }

..和PHP文件(标题部分)

@H_301_5@$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);

文件是从URL调用,如下所示:

@H_301_5@download.PHP?id=a2a9ca5bd4a84294b421fdd9ef5e438ded7fcb09

我从这里尝试了一些示例/解决方案,但到目前为止还没有工作.文件很大(每个250到400 MB),每个用户可以下载4个文件.

使用PHP下载部件没有问题,只有看起来不起作用的Nginx配置.未检测到错误日志.

最佳答案
好的 – 这里有几个问题:

1)根据Nginx开发人员的说法,在一个位置内部设置根是BAD IDEA.

2)用于告知Nginx这是内部重定向的内部URL不应向用户公开.

3)我无法看到你的download.PHP文件的来源,所以我更改了你的根位置块以使用try_files,因此对该文件而不是index.PHP的/download.PHP请求.

您的项目应该如下:

@H_301_5@project\ html - this is the root of your website protected - this directory is not accessible directly

你的Nginx conf应该是这样的:

@H_301_5@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获取内部位置:

@H_301_5@$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);

猜你在找的Nginx相关文章