'Apache2 PHP - How do I use .htaccess to rewrite direct download links

I have a directory of files which are downloaded by users package managers using the direct link to the file. I'm trying to set up file logging, so I can get statistics on the downloads. I’m using this script I found on GitHub: https://github.com/iNamik/PHP-Download-Tracker

  • I'm using the above script that consists of a files directory, a log directory, and an index.php which lists the files to download.

  • Index.php lists all files in the download directory. This file can be renamed to anything, i.e. download.php

  • If I use the index.php and click on the file I want to download, it logs the information and downloads it.

  • If I use the direct link to the file (/downloadfolder/file.exe) the index.php is bypassed and nothing is logged.

Is it possible to use something like mod_rewrite in Apache, to add download.php?file= before the file name in the direct link?

Example:

  1. Access this Direct link: https://exampledomain.com/files/file.pdf --> this does not get logged. File transfer starts.

  2. Have it be automatically rewritten to: https://exampldomain.com/files/download.php?file=file.pdf --> This does get logged. And the file transfer starts



Solution 1:[1]

After some hair pulling and testing using a htaccess tester, this is what I came up with.

My download.php is inside the files directory.

RewriteEngine On
RewriteBase /files/
RewriteRule ^(.+(file|FILE))$ download.php?file=$1 [L]

Solution 2:[2]

This will redirect anything that doesn't exist to index.php

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ index.php [L]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 user2182349