开发者

Redirect (rewrite?) all .PDF requests on Apache server to .php file

So I am building an application that necessitates redirecting (or is it rewriting? I need to do the one where the URL remains the same on the client side) to a .php file for all requests that occur for .pdf files in a given directory on my web server (Apache). However, I only want this request to be rewritten if the user is trying to display the PDF in a browser (not download it). I have a feeling this second part is not possible.

Does anyone have some good resources to look into that not only depict the syntax that I will need to use but also what is going on behind the scenes with the Apache server?

Also, does anyone have an idea as to how I can determine if the file is being directly downloaded or requested via web-browser? I have a feeling that, since when you access a PDF file via a browser, it seems to download it and display it using the Adobe Reader plugin, that there is no distinction that can be made between th开发者_高级运维e two.

Best regards,


<IfModule mod_rewrite.c>
   Options +FollowSymLinks
   Options +Indexes
   RewriteEngine On

   # only if not an actual file exist
   RewriteCond %{REQUEST_FILENAME} !-f

   # only if not an actual directory exist
   RewriteCond %{REQUEST_FILENAME} !-d

   RewriteRule /your-directory/path/(.+)\.pdf $1.php [NC,L]
</IfModule>

1. It is rewriting.

2. There is no distinction between viewing and downloading. If a request is received by your Apache server, it will give a response. The response will be whatever your PHP script will output. Update: @corretge has given you an answer related to this. I think it's not entirely reliable to rely on headers sent by the client, but you can try that solution.

3. Here you can learn about Apache's mode_rewrite


Not tested, but you can also try:

RewriteRule ^(.+)\.pdf$  /downloadPdf.php?pdf=$1.pdf [L,NC,QSA]

And in the /downloadPdf.php script query for HTTP headers with headers_list() if any of these are present:

header("Content-Type: application/force-download");
header("Content-Type: application/download");

If download headers are present, send the file with

  header("Content-Disposition: attachment; filename=\"" . stripslashes($this->ubqDoc[$this->camp]['name']) . "\"");

And the force download headers.

Else, send the file with this header

  header("Content-Disposition: inline; filename=" . stripslashes($this->ubqDoc[$this->camp]['name']));

You need to manage other headers, like Content-Type and Content-Lenght

Read the fpassthru PHP manual about send files from PHP.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜