简体   繁体   中英

htaccess: disallow all pdf files but allow from php script (file download script)

I wrote a small download script to hide the file path, the file "get_file.php" handles everything. next step I would like to disallow with htaccess all pdf-files from direct access trough the browser (if anybody knows the exact url to the file), but still provide access to the file with my "get_file.php".

I tried:

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] 
RewriteRule \.(pdf)$ - [F]

any ideas?

Try this rule at top of your .htaccess:

RewriteEngine on 

RewriteCond %{THE_REQUEST} \.pdf[?\s] [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] 
RewriteRule ^ - [F]

Just try this:

get_file.php

<?php
    // You can add extra codes to get your pdf file name here
    $file = 'file.pdf';

    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($file).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
?>

1st step - htaccess - there are different ways I usually use FilesMatch:

<FilesMatch "\.pdf$">
    Order allow,deny
    Deny from all
</FilesMatch>

2nd step is at your PHP file - you have just to use local path to load it and display it.. /path/to/file.pdf Here are examples how to export it for the clients : correct PHP headers for pdf file download

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM