仅当网站发生更改时设置缓存标头(PHP,HTaccess)
set cache headers only when something changed in the website (php, htaccess)
我正在运行wordpress。在.htaccess文件中添加了此代码,以便用户将看到最新版本的网站,而不是缓存的网站。
<IfModule mod_rewrite.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
但是现在它加载得非常慢,原因很清楚。因为每次刷新时,它都会再次加载新文件。我想知道是否有其他方法可以检测何时更改了某些内容,然后才添加这些标头或以其他方式清除缓存。不想使用任何插件。想通过一些 php 或 javascript 代码来修复它。任何帮助,不胜感激。
您可以为不同的文件扩展名设置过期标头,如下所示:
<IfModule mod_expires.c>
ExpiresActive on
# Your document html
ExpiresByType text/html "access plus 0 seconds"
# Media: images, video, audio
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/ogg "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"
# CSS and JavaScript
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType text/css "access plus 1 year"
</IfModule>
对于您知道将更定期更改的特定文件,您可以在 URL 中添加扩展名(如 ?=[timestamp]
),以便浏览器将其识别为新版本。
例如,当您希望查看者看到新版本时,可以将.js
文件更改为main.js?version=2
。
或者,您可以将扩展名更改为 main.js?ts=<?php echo date() ?>
,以便在每次访问时重新加载文件,因为时间戳每次都会不同。
编辑
另一种解决方案是使用文件的上次编辑时间(使用 filemtime()
)作为参数追加,如下所示:
<script type='text/javascript' src='main.js?fmt=<?= filemtime("main.js") ?>'>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); echo '?ver=' . filemtime( get_stylesheet_directory() . '/style.css'); ?>" type="text/css" media="all" />
这意味着文件数据更改后的第一次加载将强制刷新。
相关文章:
- 使用php或javascript从facebook相册URL中删除多余的部分
- 将PHP变量传递给jQuery时遇到问题
- 通过javascript重定向html传递php变量
- 将数组从PHP传递到Javascript
- 如何在php文件中获取$.post-ajax传递的值
- Javascript运行php文件,然后下载文件
- 在php中htaccess重定向url后,无法加载css和js
- 将javascript与htaccess和php绑定
- Javascript 到 php 处理程序页面使用 htaccess
- 通过 https 请求访问和读取 html/php 页面,由 htaccess apache2 Server 后面的 Q
- 仅当网站发生更改时设置缓存标头(PHP,HTaccess)
- .htaccess+PHP创建带有一些固定链接的动态Facebook类型导航
- 如何完善url在地址栏php,.htaccess,或javascript
- 把手机和平板电脑分开(htaccess、javascript或php)
- 是否有一种方法使用php或htaccess来防止访问url的某个部分
- 用php编写.htaccess文件来更新AJAX允许的url
- htaccess.给出410错误并重定向动态PHP页面
- 如何使某些javascript文件呈现从php使用htaccess
- .htaccess 不要让 PHP 文件在 jQuery 上加载
- 用node.js执行php:用.htaccess重定向