how to use .htaccess to silently read from the cache, if the file exists? is this possible?

六眼飞鱼酱① 提交于 2020-01-04 05:42:13

问题


i have this file structure:

/
/index.php
/test.php

/example/foo/bar/test.php

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

everything in /cache/* is a flat file (.htm) of the generated php files.

Basically what i want to do is this -

  • a user requests /index.htm (users will never see a .php in their url even if its made on the fly)
  • .htaccess checks if /cache/index.htm exists. if so, it reads from that file.
  • if /cache/index.htm doesn't exist, it serves index.php

another example

  • a user requests /example/foo/bar/test.htm
  • if /cache/example/foo/bar/test.htm exists, it reads from it
  • if it doesn't exist, the user is shown /example/foo/bar/test.php (but doesn't see the .php extension)

is this possible at all in .htaccess?

thanks

(btw i make the cache files elsewhere. so no need to making them on the fly)


回答1:


Assuming the only kind of check you want to do is an existence check, it should be possible with the following mod_rewrite rule set:

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


来源:https://stackoverflow.com/questions/3748863/how-to-use-htaccess-to-silently-read-from-the-cache-if-the-file-exists-is-thi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!