如何防止利用浏览器缓存?

时间:2018-09-10 17:51:04

标签: .htaccess iis cache-control

我已经使用GTMetrix来测试我的网站性能。总体得分还不错(93%),但是有些地方可以改进。我获得的最低分数之一是利用浏览器缓存。我的CSS/JS/IMAGE文件都没有设置到期日期。我对杠杆缓存以及如何设置到期时间不熟悉。环顾四周后,我发现人们使用.htaccess文件。我不确定在哪里创建该文件以及在文件中添加什么以设置到期时间/期限。这是我的头文件的示例:

https://example.org/CSS/Login.css (expiration not specified)
https://example.org/JS/Login.js (expiration not specified)
https://example.org/animated_favicon1.gif (expiration not specified)
https://example.org/favicon.ico (expiration not specified)
https://example.com/images/basicrecblue.gif (expiration not specified)
https://example.com/siteseal/javascript/siteseal.js (expiration not specified)

以上文件是通过GTmetrix测试确定的。任何人都可以帮助实现.htaccess文件的示例吗?如何为每种文件类型设置有效期?我在后端使用ColdFusion,在前端使用带有Bootstrap的JS,HTML5和Css。

1 个答案:

答案 0 :(得分:1)

假设您使用Apache HTTPD作为Web服务器,则可以简单地使用mod_expires module设置缓存控制。

您可以使用config全局放置指令,也可以使用.htaccess文件针对特定虚拟主机放置指令。内容应如下所示:

<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault "access plus 30 seconds"
    ExpiresByType text/html "access plus 15 days"
    ExpiresByType image/jpg "access plus 1 months"
    ExpiresByType image/png "access plus 1 months"
    ExpiresByType application/javascript "access plus 1 months"
</IfModule>

请注意,您可能必须先安装/启用mod_expires。您可以在互联网上找到更多说明。