Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

.htaccess for download of file if query string matches

I have a PDF section that I want to give users the option to either view the file in their browser, or download it to their computer. I do not want to duplicate the files so have hit upon the idea of using a query string to tell the server the force the file to download, e.g.

<a href="/path/to/pdfs/pdf.pdf?view=download">FileName</a>

In my .htaccess file for the pdfs folder, what do I need to put force the file to download if the query string is present?

What I have at the moment forces every pdf to download (instead of view):

<Files *.pdf>
    ForceType applicaton/octet-stream
</Files>

Upvotes: 1

Views: 3736

Answers (1)

LazyOne
LazyOne

Reputation: 165118

You can do something like this with mod_rewrite:

RewriteEngine On

RewriteCond %{QUERY_STRING} ^view=download$
RewriteRule .*\.pdf$ - [L,T=applicaton/octet-stream]

http://httpd.apache.org/docs/current/rewrite/flags.html#flag_t

P.S. Depending on your rewrite logic (if you have any) you may need to remove the L, flag.

The above rule will work for URLs that end with .pdf and having view=download as query string EXACTLY. This means that it will work for example.com/some/file/here/hello.pdf?view=download but will not work for example.com/some/file/here/hello.pdf?view=download&var1=param1. To have it working for such scenario as well you will have to adjust the rule accordingly (but considering the URL examples you have provided in your Question, it should not happen).

Upvotes: 7

Related Questions