重写文件路径中的 RewriteRule 检查文件是否存在 [英] RewriteRule checking file in rewriten file path exists
问题描述
如何使用ModRewrite来检查缓存文件是否存在,如果存在,则重写到缓存文件,否则重写为动态文件.
例如我有以下文件夹结构:
<前>页面.php缓存/页数/1.html2.htmltextToo.html等等.您将如何为此设置 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 才能实现.
RewriteRule ^pages/([^/\.]+) cache/pages/$1.html [NC,QSA]# 此时,我们已经将 pages/4 重写为 cache/pages/4.htmlRewriteCond %{REQUEST_FILENAME} !-f# 如果上面的 RewriteCond 成功了,我们就没有缓存,所以重写为# pages.php URI,否则我们会掉线并使用# 缓存/页面/4.htmlRewriteRule ^cache/pages/([^/\.]+).html pages.php?p=$1 [NC,QSA,L]
关闭 MultiViews 也很重要(如果您启用了它们).
选项 -MultiViews
否则初始请求 (/pages/...) 将在 mod_rewrite 启动之前自动转换为/pages.php.您也可以将 pages.php 重命名为其他名称(并更新最后的重写规则)避免多视图冲突.
我最初包括 RewriteCond ... !-d
但它是无关紧要的.
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 the following folder structure:
pages.php cache/ pages/ 1.html 2.html textToo.html etc.
How would you setup the RewriteRules for this so request can be send like this:
example.com/pages/1
And if the cache file exists rewrite tot the cache file, and if the cache file does not exists, rewrite to pages.php?p=1
It should be something like this: (note that this does not work, otherwise I would not have asked this)
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]
I can off coarse do this using PHP but I thought it had to be possible using mod_rewrite.
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.
这篇关于重写文件路径中的 RewriteRule 检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!