Nginx + PHP:将受保护的文件请求重定向到PHP脚本,然后下载文件 [英] Nginx+PHP: redirect protected file request to PHP script and then download the file
问题描述
我有一个/upload/目录,用户可以在其中上传机密文件.例如:example.com/upload/username/myfile.jpg
I have an /upload/ directory where users can upload confidential files. Ex: example.com/upload/username/myfile.jpg
我希望只有将文件上传到自己目录中的人才能访问这些文件.
I want the files to be accessible only by the person who uploaded them in her own directory.
在我的Nginx服务器配置中,我首先将所有包含上传"的位置重定向到一个PHP文件:
In my Nginx server config, I first redirect all location containing "upload" to a PHP file:
location ^~ /upload/ {
rewrite ^(.*)$ /dl-file.php?$1 break;
}
因此 http://example.com/upload/username/myfile.jpg 现在提供dl-file.php.
So http://example.com/upload/username/myfile.jpg now serves dl-file.php.
// Get the url
$url = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
// Function to download the file with the url
download_remote_file_with_curl($url, realpath("./downloads"));
该脚本尝试下载与URL http://example.com/upload相关联的文件/username/myfile.jpg .但是随后Nginx再次将请求重定向到dl-file.php.
The script tries to download the file associated with the URL http://example.com/upload/username/myfile.jpg. But then Nginx redirects the request to dl-file.php again.
因此,我最终下载了"dl-file.php"而不是"myfile.jpg".第一次使用Nginx如何重定向文件请求,然后使用PHP启用下载?
So I end up downloading 'dl-file.php' instead of 'myfile.jpg'. How can I redirect a file request the first time with Nginx but then enable the download with PHP?
(如果我的工作不可行,我愿意采取另一种方法)
(I'm open to a different approach if mine won't work)
推荐答案
如果您使用的是php,则可以使用try_files
直接提供脚本,然后执行类似$my_args = explode('/', $_SERVER['REQUEST_URI']);
的操作.
If you're using php, you could use try_files
to serve your script directly then do something like $my_args = explode('/', $_SERVER['REQUEST_URI']);
.
location ^~ /upload/ {
try_files /dl-file.php =404;
include php_fastcgi.conf; # <- php stuff here
}
这篇关于Nginx + PHP:将受保护的文件请求重定向到PHP脚本,然后下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!