如何检查使用的.htaccess缓存文件是否存在,加载正常的脚本,如果不缓存、是否存在、脚本、加载

2023-09-02 09:43:14 作者:澈

我一直在瞎搞用.htaccess文件在过去的一天,但只有适度的成功。我写了生成每个页面,并将其存储的缓存版本的 www.mysite.com/cache / 和维护的实际文件相同的目录结构缓存脚本,但它增加了html的到最后。因此,如果实际的文件是:

  www.mysite.com/blue/turtleneck
 

缓存文件将是:

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

我需要检查是否缓存版本的存在,如果是这样,加载它。如果它不存在我需要加载实际的文件。另外,我需要迫使它加载非缓存版本的某种方式。我在想也许添加 /非缓存/ 到URL的末尾来加载非高速缓存副本。例如:

  www.mysite.com/blue/turtleneck/nocache/
 
UC浏览器看视频加载到百分之九十就停了看不了了怎么办

我一直挣扎着这一点,任何帮助将是非常美联社preciated。

解决方案

使用这些规则:

 选项+了FollowSymLinks -MultiViews

RewriteEngine叙述上
的RewriteBase /

#不为已存在的文件做任何事
的RewriteCond%{} REQUEST_FILENAME -f [OR]
的RewriteCond%{} REQUEST_FILENAME -d
重写规则+  -  [L]

是否存在#发球缓存的文件
的RewriteCond%{DOCUMENT_ROOT} /cache/$1.html -f
重写规则(。*)/cache/$1.html [L]
 

这需要放置在.htaccess文件中的网站根目录。如果放在其他地方的一些调整是必须的。

该规则将检查缓存重写之前存在。

它会做的检查不存在(即#不做任何事情已存在的文件的规则将无法通过真正的文件的请求,那么远)的任何资源。

如果你愿意,你可以摆脱的#没有为已存在的文件做任何事的规则 - 它仍然应该工作正常(可能需要这么做基您的应用程序/网站的逻辑)。

如果 /缓存/ 文件夹或有问题的任何其他文件夹不是在一个网站的根目录,但别名实际的文件夹中,那么这极有可能是行不通的。

I've been messing around with .htaccess files for the past day, but with only moderate successes. I wrote a caching script that generates 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]

This needs to be placed in .htaccess file in website root folder. If placed elsewhere some tweaking may be required.

The rule will check if cache exist before rewriting.

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).

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).

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.