2013-04-22 41 views
1

我們通過單個下載鏈接分發不同版本的軟件產品。交付是基於referer連同默認值,這工作正常。另外,如果使用錯誤的文件名,用戶應該被重定向到404頁面。強制重定向某些文件(基於referer)並觸發404頁面,否則

目前的.htaccess -file看起來是這樣的:

# stop directory listing 
Options -Indexes 

# turn rewrite engine on 
RewriteEngine On 

# force 404 if file name is missing or wrong 
RewriteCond %{REQUEST_URI} !^(download_mac\.zip|download_pc\.zip)$ 
RewriteRule (.*) 404/index.html [L] 

# an example based on the referer 
RewriteCond %{HTTP_REFERER} ^http://([^.]+\.)*domain-a\.com [OR] 
RewriteCond %{HTTP_REFERER} ^http://([^.]+\.)*domain-b\.com 
RewriteRule ^(download_mac\.zip|download_pc\.zip)$ domain_ab/$1 [L] 

# last rule if no referer matches 
RewriteRule ^(download_mac\.zip|download_pc\.zip)$ default/$1 [L] 

所以我一個問題,這個文件一個額外的問題:

  1. 的第一條規則,給力404,是非常貪心,無論調用什麼URL,每時間都會得到錯誤頁面。我也嘗試了單一的陳述,如RewriteCond %{REQUEST_URI} !^download_mac\.zip$,沒有任何影響。我怎樣才能解決這個問題?
  2. 如何擺脫其他規則中的文件名?我嘗試了諸如RewriteRule ^(.*)$ default/$1 [L]之類的東西,但它讓我很難過,並且500 Internal Server Error
+2

REQUEST_URI總是以'/'開始,但是你的RewriteCond希望它開始與'download_ ...'這不可能發生。包含該RewriteCond的主要斜槓不能匹配所有內容。 – CBroe 2013-04-22 15:24:00

+0

@CBroe謝謝你指出。在其他的'.htaccess'文件中,我用你用尖括號表示的方式來使用它 - 不知何故這次它不見了。謝謝。 – insertusernamehere 2013-04-23 08:36:20

回答

1

可避免使用環境變量這樣重複你的文件名:

RewriteRule ^(download_mac\.zip|download_pc\.zip)$ - [E=ALLOWED:$1,NC] 

RewriteCond %{ENV:ALLOWED} ^$ 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule^/404/index.html [L] 

RewriteCond %{ENV:ALLOWED} !^$ 
RewriteCond %{HTTP_REFERER} ^http://([^.]+\.)*domain-a\.com [OR] 
RewriteCond %{HTTP_REFERER} ^http://([^.]+\.)*domain-b\.com 
RewriteRule^/domain_ab/%{ENV:ALLOWED} [L] 

RewriteCond %{ENV:ALLOWED} !^$ 
RewriteRule^/default/%{ENV:ALLOWED} [L] 
+0

+1非常感謝。這工作完美。我從來沒有在'.htaccess'中使用任何env變量,但現在我有一個想法如何使用它們。也爲此感謝。 – insertusernamehere 2013-04-23 08:30:39

1

你可以只移動重寫規則到底。其它的規則處理有效的情況下,如果沒有他們的最後一個規則匹配適用

# an example based on the referer 
RewriteCond %{HTTP_REFERER} ^http://([^.]+\.)*domain-[ab]\.com 
RewriteRule ^download_(mac|pc)\.zip$ domain_ab/$0 [L] 

# last rule if no referer matches 
RewriteRule ^download_(mac|pc)\.zip$ default/$0 [L] 

# force 404 if file name is missing or wrong 
RewriteRule^404/index.html [L] 
+0

+1我以前嘗試過,它沒有工作。由於你的代碼沒問題,我猜想我錯過了一些東西。感謝您的幫助。 – insertusernamehere 2013-04-23 08:38:01