缓存图像,php,js和html

时间:2011-12-30 02:26:56

标签: php html caching browser-cache

我想缓存我的所有文件,但我无法弄清楚如何让它工作以便测试批准。我目前

<meta http-equiv="Cache-Control" content="private" />
<meta http-equiv="Expires" content="86400000" />
<meta http-equiv="Cache-Control" content="max-age=86400000" />

我添加的最后一行只是为了测试是否已过期且max-age会有所帮助(它没有)

我使用的是http://www.webpagetest.org/https://developers.google.com/pagespeed/#http://gtmetrix.com/

任何人都可以告诉我如何确保一切都是私下缓存的?我检查了一堆其他页面,但没有人提供合法的HTML代码。请列出实际代码,不要只告诉我使用Cache-Control并过期,就像我见过的所有其他网站一样。我真的需要示例代码才能理解。感谢您提前提供的任何帮助。我也在使用PHP,所以如果在header()中这样做,那也可以。

非常感谢

编辑:我也尝试使用.htaccess来执行此操作,但这不起作用。我不知道它是否是我的服务器的设置或什么,但它没有改变任何测试。

2 个答案:

答案 0 :(得分:5)

在HTML文档中指定到期时间时,它仅适用于实际文档。

假设您有一个启用了mod_expires的Apache网络服务器,您可以创建一个名为.htaccess的文件并包含以下内容

ExpiresActive On
ExpiresByType image/gif       86400000
ExpiresByType image/png       86400000
ExpiresByType image/jpg       86400000
ExpiresByType image/jpeg      86400000
ExpiresByType text/html       86400000
ExpiresByType text/javascript 86400000
ExpiresByType text/plain      86400000

答案 1 :(得分:5)

您可以使用.htaccess来缓存文件。

    #cache html and htm files for one day  
<FilesMatch ".(html|htm)$">  
Header set Cache-Control "max-age=43200"  
</FilesMatch>  

#cache css, javascript and text files for one week  
<FilesMatch ".(js|css|txt)$">  
Header set Cache-Control "max-age=604800"  
</FilesMatch>  

#cache flash and images for one month  
<FilesMatch ".(flv|swf|ico|gif|jpg|jpeg|png)$">  
Header set Cache-Control "max-age=2592000"  
</FilesMatch>  

#disable cache for script files  
<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">  
Header unset Cache-Control  
</FilesMatch>