php.htaccess

how to write HTACCESS rule for parsing all files of a folder to php page along with query parameters?


I have a web app in which there is a folder named "customers" and inside this folder there are subfolder with random strings for each customer and it contains various data like PDFs , text files , images etc. I want to add some authentication so that only logged in users can view this data or they can create a simple url for sharing with tokens-(example.com/data/customers/customer1/bill_01.pdf?token=1234) .

How to write htaccess rule so that script present in "example.com/data/check.php?file=FILE_PATH&token=TOKEN1234" can determine if token is correct and just stream the data which was requested or deny when someone opens (example.com/data/customers/customer1/bill_01.pdf?token=1234) .


Solution

  • RewriteEngine On
    RewriteRule ^(.*)$ /file.php?q=$1 [NC,L,QSA]
    

    The "file.php" handles authentication and logging of access. after successful authentication , it just sends the same data that was requested.

    Also using this in file.php for handling different file types-

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $ext = finfo_file($finfo,$q);
    header('Content-Type: '.$ext);