Use .htaccess to limit access to file downloads
I have downloads for static files like product.exe. I want to limit access to these files with a .htaccess file so that only certain users can download it.
I think this can be handled with mod_rewrite and I found this snippet online that blocks bad sites using the referrer.
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} http://example.com/downloads/confirm/3811 [NC,OR]
RewriteRul开发者_如何学Pythone .* - [F]
Source: http://www.javascriptkit.com/howto/htaccess14.shtml
Instead of blocking based on referrer, I want to allow based on referrer. That way, the referrer can be a URL that cannot be accessed without first logging in. I am thinking about going this route and using the http referrer to give permission to the file. I know it may not be the best way to do it, and I guess the referrer can be spoofed, but it does not have to be THAT secure. I am also open to other ideas you may have to for limitting access.
If you want to allow based on Referrer:
RewriteCond %{HTTP_REFERER} !^http://goodsite-1.com/ [NC]
RewriteCond %{HTTP_REFERER} !^http://goodsite-2.com/from/there.php [NC]
RewriteCond %{HTTP_REFERER} !^$ # There are some users/browsers not sending referrer..
RewriteRule .* - [F]
Or you can allow based on a cookie, which you can set before with e.g. PHP:
RewriteCond %{HTTP_COOKIE} !^.*cookie-name.*$ [NC]
RewriteRule .* - [F]
Or also only allow Post requests:
RewriteCond %{REQUEST_METHOD} !=POST
RewriteRule .* - [F]
and your Link for 'post request' in your HTML to the file to download:
<form method="post" action="path/to/download.mp3">
<input type="submit" value="Click here to download!" />
</form>
Actually you could combine these methods.
Due to some security matters http_referrer is not a reliable header.
- Some browser configurations cause an empty http_referrer header
- There are tools that you can manipulate http request headers. You can take a look at Firefox developer tools.(Ctrl + Shift + I > Network)
精彩评论