2015-08-26 14 views
0

如何使用mod_rewrite/media/中的所有文件指定爲http://anothersite.com/media?我正在將暫存網站的圖片請求引導至其主目錄。mod_rewrite將目錄中的資產分配給另一臺服務器

下不工作:

<IfModule mod_rewrite.c> 
    RewriteEngine On 
    RewriteBase/
    RewriteRule ^media/(.*) http://anothersite.com/$1 [QSA,L] 
</IfModule> 

未與Apache的配置搞砸了 - 原諒我,如果這是一個跛腳鄰問題。

+1

可以使用:'重寫規則^(媒體/.*)http://anothersite.com/$1 [R = 301,NC,L]' – anubhava

+0

論'/媒體的請求/ image1.jpg'例如,你想服務於'http:// anotheriteite.com/media/image1.jpg'或'http:// anotheriteite.com/image1.jpg'中的內容嗎?問題中的第一句話告訴你想要第一個URL,'RewriteRule'讓你成爲第二個URL。哪一個? – axiac

+0

@axiac後者 - 現在覆蓋着GentlemanMax的回答 – technopeasant

回答

2

既然你是重定向到另一個網站,我相信你需要調用mod_proxy而不是mod_rewrite。你可以通過將[QSA, L]更改爲[P]。所以像這樣:

<IfModule mod_rewrite.c> 
     RewriteEngine On 
     RewriteBase/
     RewriteRule ^media/(.*) http://anothersite.com/media/$1 [P] 
</IfModule> 

否則,你的重寫規則看起來不錯。

一個可能更好的替代方案是將本地PHP腳本加載並返回您重定向到的圖像。

在這種情況下,你的重寫規則是這樣的:

<IfModule mod_rewrite.c> 
     RewriteEngine On 
     RewriteBase/
     RewriteRule ^media/(.*) /imageFetcher.php?img=$1 [QSA, L] 
</IfModule> 

然後,你需要創建一個文件imageFetcher.php。用下面的

<?php 
    //Do some checks to make sure this request came from your site, you won't want external users accessing this script 
    $img_file = $_GET['img']; 
    $img_data = file_get_contents("http://anothersite.com/$img_file"); 

    //Possibly verify that $img_data is a valid image file using imgjpeg(), imgpng(), etc 

    header('Content-Type: image/jpeg'); //This assumes your image is a jpeg. If the image could be a png/gif/etc you'll need to do some logic to set the proper header. 
    echo $img_data; 
    exit(); 
+0

Hrm,這也不適合我。我可以將這些請求記錄到文件中進行審閱嗎?錯誤修復這個服務器的東西超出了我 – technopeasant

+0

我通常使用像[this]這樣的測試器(http://htaccess.madewithlove.be/)。您是否考慮過使用本地php腳本來從遠程服務器上獲取文件? – GentlemanMax

+0

我編輯了我的解決方案,以包含一個php fetcher作爲可能的解決方案。 – GentlemanMax

相關問題