2009-01-22 85 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] 
相关问题