Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It's possible to force download with .htaccess and a specific GET request (Dropbox style)?

I wonder if it's possible with .htaccess to force files to download only if there is a specific GET variable, just like Dropbox does.

Example:

http://www.domain.com/file.mp4

the server just serves the file, while:

http://www.domain.com/file.mp4?dl

force the browser to download the file.

PS: Using PHP with readfile() it's not a viable option in my case. Thanks.

like image 369
null Avatar asked Dec 05 '22 17:12

null


2 Answers

The pattern of FilesMatch doesn't match against the query string, only the filename proper.

You could, however, make use of mod_rewrite module, the %{QUERY_STRING} variable and the T flag:

RewriteCond %{QUERY_STRING} dl
RewriteRule .*\.mp4 - [T=application/octet-stream]

Alternatively, if you have Apache > 2.3 (I think), you can use the If directive, which is a lot cleaner:

<FilesMatch "filepattern.mp4">
   <If "%{QUERY_STRING} =~ /dl/">
      ForceType application/octet-stream
      Header set Content-Disposition attachment
   </If>
</FilesMatch>

First solution was updated.

like image 113
SáT Avatar answered Dec 07 '22 07:12

SáT


I have a very similar requirement on my project. The question actually gave me the idea of using a query parameter similar to how DropBox handles download links. I'm going to use longer "dl=1" parameter like DropBox does so its unlikely to show up in a normal URL. Using the Apache "if directive" is a great idea but unfortunately I'm on Apache 2.2 so that is not available. I considered using application/octet-stream Content-Type but then I saw this other Stack Overflow thread that did not like that idea. So finally I saw a BlogSpot Article that suggested setting an Environment Variable in a RewriteRule and referencing that same Variable in a Header Command. The .htaccess code works quite nicely and solved the problem. Thanks to everyone on this thread and the BlogSpot guy for the great suggestions. My code sample is listed below:

# Required Modules are:
# 1) mod_rewrite.c
# 2) mod_headers.c
RewriteEngine On
RewriteCond %{QUERY_STRING} ^dl=1
RewriteRule .* - [E=DOWNLOAD_FILE:1]
Header set Content-Disposition "attachment" env=DOWNLOAD_FILE
like image 24
jambroseclarke Avatar answered Dec 07 '22 07:12

jambroseclarke