2009-01-22 33 views
14

如何使用ModRewrite檢查緩存文件是否存在,如果存在,請重寫到緩存文件,否則重寫爲動態文件。RewriteRule檢查文件存在重寫文件路徑

,比如我有以下文件夾結構:

 
pages.php 
cache/ 
    pages/ 
    1.html 
    2.html 
    textToo.html 
    etc. 

你會如何設置此所以請求的RewriteRules可以這樣發:

 
example.com/pages/1 

如果緩存文件存在重寫如果緩存文件不存在,重寫爲pages.php?p = 1

它應該是這樣的:(注意,這是行不通的,否則我不會問這個)

​​

我可以粗糙使用PHP做這個,但我認爲它必須可能使用mod_rewrite。

回答

17
RewriteRule ^pages/([^/\.]+) cache/pages/$1.html [NC,QSA] 

# At this point, we would have already re-written pages/4 to cache/pages/4.html 
RewriteCond %{REQUEST_FILENAME} !-f 

# If the above RewriteCond succeeded, we don't have a cache, so rewrite to 
# the pages.php URI, otherwise we fall off the end and go with the 
# cache/pages/4.html 
RewriteRule ^cache/pages/([^/\.]+).html pages.php?p=$1 [NC,QSA,L] 

關閉MultiViews至關重要(如果您啓用了它們)。

Options -MultiViews 

否則初始請求(/頁/ ...)將獲得自動轉換的mod_rewrite在踢之前/pages.php。你也可以重新命名pages.php到別的東西(和更新的最後一個重寫規則)以避免MultiView衝突。

編輯:我最初包括RewriteCond ... !-d但它是無關的。

5

另一種方法是,首先看是否有可用的chached表示:

RewriteCond %{DOCUMENT_ROOT}/cache/$0 -f 
RewriteRule ^pages/[^/\.]+$ cache/$0.html [L,QSA] 

RewriteRule ^pages/([^/\.]+)$ pages.php?p=$1 [L,QSA] 
相關問題