RewriteRule checking file in rewriten file path exists

后端 未结 2 1331
说谎
说谎 2020-12-03 02:18

How can you use ModRewrite to check if a cache file exists, and if it does, rewrite to the cache file and otherwise rewrite to a dynamic file.

For example I have th

相关标签:
2条回答
  • 2020-12-03 02:27

    Another approach would be to first look if there is a chached representation available:

    RewriteCond %{DOCUMENT_ROOT}/cache/$0 -f
    RewriteRule ^pages/[^/\.]+$ cache/$0.html [L,QSA]
    
    RewriteRule ^pages/([^/\.]+)$ pages.php?p=$1 [L,QSA]
    
    0 讨论(0)
  • 2020-12-03 02:47
    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]
    

    Turning off MultiViews is crucial (if you have them enabled) as well.

    Options -MultiViews
    

    Otherwise the initial request (/pages/...) will get automatically converted to /pages.php before mod_rewrite kicks in. You can also just rename pages.php to something else (and update the last rewrite rule as well) to avoid the MultiViews conflict.

    Edit: I initially included RewriteCond ... !-d but it is extraneous.

    0 讨论(0)
提交回复
热议问题