首页 文章

存在重写文件路径中的RewriteRule检查文件

提问于
浏览
14

如何使用ModRewrite检查缓存文件是否存在,如果存在,则重写缓存文件,否则重写为动态文件 .

例如,我有以下文件夹结构:

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

你如何为此设置RewriteRules,所以请求可以像这样发送:

example.com/pages/1

如果缓存文件存在,则重写缓存文件,如果缓存文件不存在,则重写为pages.php?p = 1

它应该是这样的:(请注意,这不起作用,否则我不会问这个)

RewriteRule ^pages/([^/\.]+) cache/pages/$1.html [NC,QSA]
RewriteCond %{REQUEST_FILENAME} -f [NC,OR] 
RewriteCond %{REQUEST_FILENAME} -d [NC] 
RewriteRule cache/pages/([^/\.]+).html pages.php?p=$1 [NC,QSA,L]

我可以使用PHP来粗略地做这个,但我认为必须使用mod_rewrite .

2 回答

  • 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
    

    否则初始请求(/ pages / ...)将在mod_rewrite启动之前自动转换为/pages.php . 您也可以将pages.php重命名为其他内容(并更新上一次重写规则)以避免MultiViews冲突 .

    编辑:我最初包括 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]
    

相关问题