如果文件存在,如何使用 .htaccess 从缓存中静默读取?这可能吗?

2024-01-10

我有这个文件结构:

/
/index.php
/test.php

/example/foo/bar/test.php

/cache/index.htm
/cache/test.htm
/cache/foo/bar/test.htm

/cache/* 中的所有内容都是生成的 php 文件的平面文件 (.htm)。

基本上我想做的是这样的 -

  • 用户请求/index.htm(用户 永远不会在他们的网址中看到 .php 即使它是即时制作的)
  • .htaccess 检查是否/cache/index.htm存在。如果是这样,它会从中读取 文件。
  • if /cache/index.htm不 存在,它服务于index.php

另一个例子

  • 用户请求/example/foo/bar/test.htm
  • if /cache/example/foo/bar/test.htm存在,它从中读取
  • 如果不存在,则显示用户/example/foo/bar/test.php(但没有看到 .php 扩展名)

在 .htaccess 中这可能吗?

thanks

(顺便说一句,我在其他地方制作了缓存文件。所以不需要即时制作它们)


假设您想要执行的唯一检查是存在检查,则应该可以使用以下方法模组重写 http://httpd.apache.org/docs/current/mod/mod_rewrite.html规则集:

RewriteEngine On

# Check if a PHP page was requested
RewriteCond %{THE_REQUEST} ^[A-Z]+\s/[^\s]+\.php
# If so, redirect to the non-cache .htm version
RewriteRule ^(.*)\.php$ /$1.htm [R=301,L]

# Check if the file exists in the cache
RewriteCond %{DOCUMENT_ROOT}/cache/$0 -f
# If it does, rewrite to the cache file
RewriteRule ^.*$ /cache/$0 [L]

# Check that the file doesn't exist (we didn't go to the cache)
RewriteCond %{REQUEST_FILENAME} !-f
# Check that the request hasn't been rewritten to the PHP file
RewriteCond %{REQUEST_URI} !\.php$
# If both are true, rewrite to the PHP file
RewriteRule ^(.*)\.htm$ /$1.php
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果文件存在,如何使用 .htaccess 从缓存中静默读取?这可能吗? 的相关文章

随机推荐