HTML - Cache control max age

孤街醉人 提交于 2019-12-03 10:56:50
calumbrodie

There is more than one way to do this - but you need to consider exactly what you need to cache and what you don't. The biggest speed increases will likely come from making sure your assets (css, images, javascript) are cached, rather than the html itself. You then need to look at various factors (how often do these assets change, how will you force a user to download a new version of the file of you do change it?).

Often as part of a sites release process, new files (updated files) are given a new filename to force the users browser to redownload the file, but this is only one approach.

You should take a look at apache mod_expire, and the ability to set expiry times for assets using the .htaccess file.

http://www.google.com/?q=apache+cache+control+htaccess#q=apache+cache+control+htaccess

The Cache-Control header is used in HTTP 1.1 to control the behavior of caches. The max-age directive is used to specify (in seconds) the maximum age of the content before it becomes stale (i.e., the content will not change for some period of time). So if you know that your content will not change for 3 days, you want your server to add the following HTTP header:

Cache-Control: max-age=259200

(259200 = 60s x 60m x 24h x 3d)

To do that in PHP, add this line to your output:

header('Cache-Control: max-age=259200');

Read here for more info on the header function:

As mentioned Expires and Cache-Control Headers are usually the best way to incorporate information about information lifetime.

Because clients are not very reliable on interpreting these informations proxies with caching capabilities like squid, varnish or such solutions are preferred by most people. You also need to consider if you want to cache only static content (like images, stylesheets, ..) or dynamically generated content as well.

As per the YSlow recommendations you could configure your web server to add an Expires or a Cache-Control HTTP header to the response which will result in user agents caching the response for the specified duration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!