Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL Rewriting to Privately Access Files

I'm trying to build a simple website which is going to let users upload files, and privately share them with other designated users. The problem is: I don't want anyone to be able to type in the url for a file to be able to get to it (then anyone could see it).

I decided to try using .htaccess to prevent direct url access, however, I cannot figure out how to access the file myself. All of the uploaded files are going to go into a subfolder called "restricted".

My ".htaccess" file is:

RewriteEngine on
RewriteCond {%QUERY_STRING} !^.*key=SECRET.*$ [NC]
RewriteRule ^restricted/(.*)$ showfile.php?file=$1

My "showfile.php" file:

<?php
echo file_get_contents('[...]/restricted/'.$_GET['file'].'?key=SECRET');
?>

However, when I open "restricted/test.txt" or some other file in the restricted folder, it successfully redirects to "showfile.php?file=test.txt", however, I get a php error:

Warning: file_get_contents([...]/restricted/test.txt?key=SECRET) [function.file-get-contents]: failed to open stream: No such file or directory in [...]/showfile.php on line 10

It seems like even though the query string contains "key=SECRET", it is still trying to redirect.

What I want: I want it to redirect on direct URL access, but that I can access it through the php page it's redirected to.

like image 706
Lambda Avatar asked Dec 30 '25 23:12

Lambda


2 Answers

If you want to access the file as an HTTP resource instead of direct disk access (like in your question), you can do the following:

Code in .htaccess (placed the "nonpublic_test" folder):

RewriteEngine on
RewriteCond %{REQUEST_URI} ^.*/restricted/.*$ [NC]
RewriteCond %{QUERY_STRING} !^.*key=SECRET.*$ [NC]
RewriteRule ^(.*)$ /$1 [R=403,L]

Then in your showfile.php:

<?php
echo file_get_contents('http://www.domain.name.here/restricted/'.$_GET['file'].'?key=SECRET');
?>

This will prevent any access to the restricted folder and its contents but still allow your showfile.php script to access the file inside that folder and output it.

like image 151
arvind.d Avatar answered Jan 02 '26 12:01

arvind.d


It would be better off to move restricted folder a level above site root and have your PHP code in showfile.php like this:

<?php
   echo file_get_contents('/path/to/restricted/'.$_GET['file']);
?>

With rule simply as:

RewriteEngine on

RewriteRule ^restricted/(.*)$ showfile.php?file=$1 [L,QSA,NC]
like image 27
anubhava Avatar answered Jan 02 '26 12:01

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!