代码之家  ›  专栏  ›  技术社区  ›  Pim Jager

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

  •  14
  • Pim Jager  · 技术社区  · 17 年前

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

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

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

    您将如何设置此请求的重写规则,以便按如下方式发送请求:

    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 年前
        1
  •  18
  •   Sean Bright Sean Stinehour    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]
    

    关闭“多视图”(MultiView)也很重要(如果已启用)。

    Options -MultiViews
    

    否则,在mod_rewrite启动之前,初始请求(/pages/…)将自动转换为/pages.php。您还可以将pages.php重命名为其他名称(并更新最后的重写规则),以避免多视图冲突。

    编辑:我最初包括 RewriteCond ... !-d 但这是无关的。

        2
  •  6
  •   Gumbo    17 年前

    另一种方法是首先查看是否有可用的变形表示:

    RewriteCond %{DOCUMENT_ROOT}/cache/$0 -f
    RewriteRule ^pages/[^/\.]+$ cache/$0.html [L,QSA]
    
    RewriteRule ^pages/([^/\.]+)$ pages.php?p=$1 [L,QSA]
    
        3
  •  0
  •   Luc sra    4 年前

    RewriteCond %{REQUEST_FILENAME} !-f
    

    肖恩·布莱特的回答为缓存问题提供了一个很好的例子,但这一行适用范围更广。在我的例子中,我有一个链接缩短器,人们可以在其中选择自定义URL,我不希望它能够覆盖现有文件,例如 favicon.ico . 在重写规则之前添加此行修复了该问题。

    推荐文章