【问题标题】:htaccess->show file if in cache directory, if not continuehtaccess->如果在缓存目录中则显示文件,如果不继续
【发布时间】:2013-11-14 09:06:19
【问题描述】:

我正在玩缓存。我想要的是以下逻辑:

if ( file_exist(/cache/$request_uri.txt) ){ 
    1. show that file
    2. Stop all rewrite actions, but perform other actions (like charset, error_pages)
}
else{
    do whatever you normally do
}

小例子。我有以下文件
http://domain.com/example-123.htm(请求的页面)
http://domain.com/cache/example-123.htm.txt(该页面的缓存版本)

http://domain.com/someDir/example-456.htm(请求的页面)
http://domain.com/cache/someDir/example-456.htm.txt(该页面的缓存版本)

我不想让 index.php 解析 url 并构建页面,而是显示该文件并停止。

我虽然会这样做,但它不会:

RewriteCond ^cache%{REQUEST_URI}\.txt -f # check if the file exists in cache dir
RewriteRule ^(.*) /cache/$1\.txt [L] # i so, rewrite rule to it and stop

根据我的备忘单,[L] 确实是“最后 - 停止处理规则”。如果这仅意味着重写规则,那就是我需要的。
我不能让它工作,我可以用正确的方向推动:)


我已将答案标记为解决方案,完全按照它应该做的。我希望在 .htaccess 文件中使用它的原因是因为这样我的 index.php 不会被调用,数据库也不会被调用。一种非常快速和轻便的方法。
但是,这会产生一个新问题:某些项目(如菜单)可以(经常)更改。这意味着我必须在每次更改时删除所有缓存文件,这会阻止它高效工作。
为了解决这个问题,我想看看我是否可以使用一些聪明的 .shtml 文件来解决这个问题(可能需要允许 php 在 shtml 文件中使用)。
一旦我有一些对感兴趣的人有用的东西,我会立即更新这篇文章

【问题讨论】:

    标签: regex apache .htaccess caching mod-rewrite


    【解决方案1】:

    你可以试试这个规则:

    # check if the file exists in cache dir
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}cache/$1.txt -f
    RewriteRule ^(.+?)/?$ /cache/$1.txt [L]
    

    【讨论】:

    • %{DOCUMENT_ROOT} 部分对我有用,谢谢。它向我展示了一个 txt 文件而不是一个 html 页面:P 没想到,但我得到了原理。
    • 好的,很高兴知道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2014-03-15
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 2010-10-17
    相关资源
    最近更新 更多