Search code examples
php.htaccess

Prevent direct access to file on webserver, but make it accessable from a webpage


On my homepage I use this code:

 <audio><source src="/files/audio/x.mp3" type="audio/mpeg"></audio>

I want my homepage to display the audioplayer, but when someone enters the url (https://www.website.com/files/audio/x.mp3) the user should be blocked from opening the file.

I found several "solutions" using .htaccess and a seperate php-file for checking, but none of them worked for me (or I did something wrong...)

Could someone help me with this?

I tried to add a redirect through .htaccess. The file was blocked from viewing from the direct url, but also didn't show up in the audioplayer on the homepage...


Solution

  • NOTE

    This is extremally light on security .. Anyone who wants the file can just spoof the URL in the headers, and easily access your file.. This is just a way to keep honest people honest. It's really not a thorough security solution for "protecting" your files. If you REALLY want to do that, you should have some sort of authentication, where users log in to view your content.

    That said...

    The easy way to do it is just through .htaccess. Create yourself a 403 (Not Authorized) Page .. Here we'll call it 403.html in your root directory. Then put this htaccess in your audio directory. A also added a small block that will allow you to filter by file type if so desired.

    This will check for both www and non-www versions of your domain.

    It is important to note that the Deny comes first before the Allow. This allows us to Deny all and then allow based on the file check and referrer check.

    ErrorDocument 403 /403.html
    SetEnv deny=0
    SetEnvIf Referer "^https://yourdomain\.com/" deny=1
    SetEnvIf Referer "^https://www\.yourdomain\.com/" deny=1
    
    
    <FilesMatch "\.(mp3|mp4|mpg|jpg|gif)$">
       Order Deny,Allow
       Deny from env=deny
    </FilesMatch>