Nginx+PHP: redirect protected file request to PHP

2019-09-12 08:16发布

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.

In my Nginx server config, I first redirect all location containing "upload" to a PHP file:

location ^~ /upload/ {
  rewrite ^(.*)$ /dl-file.php?$1 break;
}

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"));

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.

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)

1条回答
唯我独甜
2楼-- · 2019-09-12 08:40

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
}
查看更多
登录 后发表回答