开发者

How to check if a file exists in cache using .htaccess, load normal script if not

I've been messing around with .htaccess files for the past day, but with only moderate successes. I wrote a caching script that generates开发者_Go百科 a cached version of each page and stores it in www.mysite.com/cache/ and maintains the same directory structure of the actual file, but it adds .html to the end. So if the actual file was:

www.mysite.com/blue/turtleneck

the cache file would be:

www.mysite.com/cache/blue/turtleneck.html

I need to check if the cached version exists and if so, load it. If it doesn't exist I need to load the actual file. Also, I need some way of forcing it to load the non-cached version. I was thinking perhaps adding /nocache/ to the end of the URL to load the noncached copy. Example:

www.mysite.com/blue/turtleneck/nocache/

I've been struggling with this and any help would be very appreciated.


Use these rules:

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

# do not do anything for already existing files
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]

# serve cached file if exists
RewriteCond %{DOCUMENT_ROOT}/cache/$1.html -f
RewriteRule (.*) /cache/$1.html [L]
  1. This needs to be placed in .htaccess file in website root folder. If placed elsewhere some tweaking may be required.

  2. The rule will check if cache exist before rewriting.

  3. It will do the check for ANY resource that does not exist (the "# do not do anything for already existing files" rule will not pass requests for real files that far).

  4. If you wish, you can get rid of "# do not do anything for already existing files" rule -- it still should work OK (it may be required to do so based on your app/website logic).

  5. If /cache/ folder or any other folder in question is not actual folder within a website root but alias, then this most likely will not work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜