How to rewrite and set headers at the same time in Apache

好久不见. 提交于 2019-12-05 21:46:12

Simple php solution:

download.php

header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename='.$_GET['img']);
readfile('gallery/'.$_GET['img']);

.htaccess

<Directory /var/www/download>
    RewriteEngine on
    RewriteRule (.*)$ /download.php?img=$1
</Directory>

A combined solution could be the following setup. First change the directory entry:

<Directory /var/www/download>
    RewriteEngine on
    RewriteRule (.*)$ download.php?getfile=$1
</Directory>

The download.php should contain something like this (NOT TESTED):

<?php

if ($_GET['getfile']){
  $file = '/var/www/gallery/' . $_GET['getfile'];
}

$save_as_name = basename($file);   
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: no-cache');
header("Content-Type: application/octet-stream");
header("Content-Disposition: disposition-type=attachment; filename=\"$save_as_name\"");

readfile($file);
?>

This shouldd redirect all download requests to download.php which in turn handles the requests and forces the saveas dialog to appear.

Paul

I just did this, after stumbling on your example ;-) I'm pretty sure you just have to change your "Directory /var/www/download" section to a "Location /download" in your latest example and you're OK.

Rationale is : "Directory" applies to the resulting physical directory, AFTER the rewrites have occured, whereas "Location" applies to the original URI, no matter any rewrites have occured to find the physical file.

As mod_rewrite is a huge hack that applies at various times, the effect of your code is not very obvious.

What I have in my workjing setup is :

<Location /contents/>
    Header set Content-Disposition "attachment"
</Location>
...
RewriteRule ^.*(/e-docs/.*)$   $1

So URLs like /contents/myimage.jpg AND /contents/e-docs/myimage.jpg both get the Content-Disposition header, even though /contents/e-docs/myimage.jpg is actually the /e-docs/myimage.jpg file, as the rewrite says.

Avoiding PHP for this have the added benefit that you can serve these images and potentially huge video files (as in my case) with a lightweight static Apache server, not a memory-hog PHP back-end process.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!