问题
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.htmexists. if so, it reads from that file. - if
/cache/index.htmdoesn't exist, it serves index.php
another example
- a user requests
/example/foo/bar/test.htm - if
/cache/example/foo/bar/test.htmexists, 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