服务器正在缓存JS文件或嵌入HTML脚本

Server is caching JS files or embedded HTML scripts?

本文关键字:HTML 脚本 文件 缓存 JS 服务器      更新时间:2023-09-26

我在我的一个网站的服务器上得到了一个异常,我需要你的帮助找到一个解决方案。

如果我打开一个由FtpZilla下载的PHP文件并编辑任何PHP代码,一旦我保存并重新上传该文件,新内容将生效。对于任何HTML代码

都是一样的

如果在同一个文件上,我编辑一些HTML代码,其中有一个<script></script>标签和里面的javascript代码,当我上传文件的新版本时,JS代码被提供给浏览器是旧的。我尝试用CTRL+F5,几个浏览器:没有出路。同样令人失望的结果,从"时间开始"开始清理每个浏览器的缓存

重新打开刚刚上传的文件,惊讶地发现我的新代码。就像服务器在提供旧文件一样。但是为什么只有JS部分呢?

不仅

:我得到了同样的问题为任何JS外部文件。我的意思是这些文件嵌入了标签<script src=""></script>到HTML页面

我试图在。htaccess中禁用任何缓存命令,如下图所示。但在这种情况下,也没有更好的事情发生。

我还能做什么?

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
# Enable expirations.
  ExpiresActive On
      # Cache all files for 2 weeks after access (A).
      #ExpiresDefault A1209600
      <FilesMatch '.php$>
        # Do not allow PHP scripts to be cached unless they explicitly send cache
        # headers themselves. Otherwise all scripts would have to overwrite the
        # headers set by mod_expires if they want another caching behavior. This may
        # fail if an error occurs early in the bootstrap process, and it may cause
        # problems if a non-Drupal PHP file is installed in a subdirectory.
        ExpiresActive Off
      </FilesMatch>
        #ExpiresByType image/jpg "access 1 year"
        #ExpiresByType image/jpeg "access 1 year"
        #ExpiresByType image/gif "access 1 year"
        #ExpiresByType image/png "access 1 year"
        #ExpiresByType text/css "access 1 month"
        #ExpiresByType application/pdf "access 1 month"
        #ExpiresByType text/x-javascript "access 1 month"
        #ExpiresByType application/x-shockwave-flash "access 1 month"
        #ExpiresByType image/x-icon "access 1 year"
        #ExpiresDefault "access 2 days"
    </IfModule>
编辑:

我刚刚注意到:如果我创建一个指向原始JS文件的符号链接,当我通过符号链接读取文件时(因此在浏览器中我调用SymLink而不是文件):我仍然得到旧版本。甚至打开它(编辑)FileZilla。就像指针永远指向旧版本。而如果我去读JS文件直接(直接调用它,甚至不通过嵌入的链接),我可以得到新版本我越来越迷路了。

ExpiresActive Off实际上会使您的浏览器缓存内容,因为服务器没有设置缓存规则。如果你想禁用缓存,你可以这样做:

<FilesMatch "'.(html)$">
    Header set Cache-Control "private, no-cache, must-revalidate"
    Header set Pragma "no-cache"
</FilesMatch>

这将告诉你的浏览器在每次请求时检查新内容。如果内容不是动态创建的(例如php),并且自上次收到它以来文件没有被修改,apache将发送一个304 not modified标头,没有数据(因为您的浏览器已经有最新版本)