簡體   English   中英

如何在Apache中同時重寫和設置標題

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

我有一個圖像目錄,可以在瀏覽器中直接查看,其他時候下載。

所以,假設我有一個文件/gallery/gal_4254.jpg。

我想讓/download/gal_4254.jpg觸發下載圖像而不是查看它。 / download為空,所有圖像都在/ gallery中。

我可以成功地將對下載目錄的請求映射到其他文件

<Directory /var/www/download>
    RewriteEngine on
    RewriteRule (.*)$ /gallery/$1
</Directory>

我已經可以通過設置強制在gallery dir中下載

<Directory /var/www/gallery/>
    ForceType "image/jpg"
    Header set Content-Disposition "attachment"
</Directory>

所以設置標題是沒問題的。 我實際上並不希望/ gallery有標題,只需要重寫/ gallery / * through / download /。

但是,我需要將兩者結合起來,因此請求被映射到另一個目錄中的文件,並且文件被賦予附件頭。

#does not work - just views the image like when it is viewed directly
<Directory /var/www/download>
    ForceType "image/jpg"
    Header set Content-Disposition "attachment"
    RewriteEngine on
    RewriteRule (.*)$ /gallery/$1
</Directory>

我試過改變重寫和標題部分的順序無濟於事。 我認為當請求被重寫到另一個目錄時它會丟失標題。

有關如何在Apache中執行此操作的任何建議?

我意識到這也可以用PHP完成,這就是我在這里發布它與服務器故障的原因。 使用PHP的解決方案也是受歡迎的。

組合解決方案可以是以下設置。 首先更改目錄條目:

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

download.php應該包含這樣的東西(未測試):

<?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);
?>

這應該將所有下載請求重定向到download.php,而download.php又處理請求並強制顯示saveas對話框。

保羅

簡單的php解決方案

的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>

我剛剛在你的例子上磕磕絆絆之后做了這件事;-)我很確定你只需要在最新的例子中將你的“目錄/ var / www / download”部分改為“Location / download”,你就可以了。

基本原理是:“目錄”適用於生成的物理目錄,在重寫發生之后,而“位置”適用於原始URI,無論是否發生任何重寫以查找物理文件。

由於mod_rewrite是一個在不同時間適用的巨大hack,因此代碼的效果不是很明顯。

我在workjing設置中的內容是:

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

所以像/contents/myimage.jpg和/contents/e-docs/myimage.jpg這樣的網址都獲得了Content-Disposition標題,即使/contents/e-docs/myimage.jpg實際上是/ e-docs / myimage。 jpg文件,正如重寫所說。

為此避免使用PHP還有一個額外的好處,即您可以使用輕量級靜態Apache服務器提供這些圖像和潛在的大型視頻文件(如我的情況),而不是內存占用的PHP后端進程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM