apache 重写文件路径中的 RewriteRule 检查文件是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/470880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RewriteRule checking file in rewriten file path exists
提问by Pim Jager
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.
如何使用 ModRewrite 检查缓存文件是否存在,如果存在,则重写到缓存文件,否则重写为动态文件。
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:
您将如何为此设置 RewriteRules,以便可以像这样发送请求:
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
并且如果缓存文件存在则重写缓存文件,如果缓存文件不存在则重写为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/.html [NC,QSA]
RewriteCond %{REQUEST_FILENAME} -f [NC,OR]
RewriteCond %{REQUEST_FILENAME} -d [NC]
RewriteRule cache/pages/([^/\.]+).html pages.php?p= [NC,QSA,L]
I can off coarse do this using PHP but I thought it had to be possible using mod_rewrite.
我可以使用 PHP 粗略地做到这一点,但我认为它必须使用 mod_rewrite 成为可能。
回答by Sean Bright
RewriteRule ^pages/([^/\.]+) cache/pages/.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= [NC,QSA,L]
Turning off MultiViews is crucial (if you have them enabled) as well.
关闭 MultiViews 也很重要(如果您启用了它们)。
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.
否则,初始请求 (/pages/...) 将在 mod_rewrite 启动之前自动转换为 /pages.php。您也可以将 pages.php 重命名为其他名称(并更新最后的重写规则)以避免多视图冲突。
Edit: I initially included RewriteCond ... !-dbut it is extraneous.
编辑:我最初包括RewriteCond ... !-d但它是无关紧要的。
回答by Gumbo
Another approach would be to first look if there is a chached representation available:
另一种方法是首先查看是否有可用的 chached 表示:
RewriteCond %{DOCUMENT_ROOT}/cache/##代码## -f
RewriteRule ^pages/[^/\.]+$ cache/##代码##.html [L,QSA]
RewriteRule ^pages/([^/\.]+)$ pages.php?p= [L,QSA]

