使用 PHP 和 Apache 设置 HTTP 过期标头 [英] Setup HTTP expires headers using PHP and Apache

查看:38
本文介绍了使用 PHP 和 Apache 设置 HTTP 过期标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 PHP + Apache 中设置过期标头?我目前正在使用 auto_prepend 来提供压缩后的资源,但我也想最大化 HTTP 缓存.

How can I setup expires headers in PHP + Apache? I'm currently using an auto_prepend to serve resources gzipped but I'd also like to maximise the HTTP cache.

如何设置这些?

推荐答案

有两种方法可以做到这一点.第一个是在你的 php 代码中指定标题.如果您想以编程方式调整到期时间,这很好.例如,wiki 可以为不经常编辑的页面设置更长的过期时间.

There are two ways to do this. The first is to specify the header in your php code. This is great if you want to programatically adjust the expiry time. For example a wiki could set a longer expires time for a page which is not edited very often.

header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60))); // 1 hour

您的第二个选择是创建一个 .htaccess 文件或修改您的 httpd 配置.在共享主机环境中,修改 .htaccess 文件是很常见的.为此,您需要知道您的服务器是否支持 mod_expiresmod_headers 或两者.最简单的方法就是反复试验,但某些 Apache 服务器配置为允许您通过/server-info 页面查看此信息.如果您的服务器同时具有 mod_expires 和 mod_headers,并且您想在静态资源上设置到期时间,请尝试将其放入您的 .htaccess 文件中:

Your second choice is to create an .htaccess file or modify your httpd config. In a shared hosting environment, modifying your .htaccess file is quite common. In order to do this, you need to know if your server supports mod_expires, mod_headers or both. The easiest way is simply trial and error, but some Apache servers are configured to let you view this information via the /server-info page. If your server has both mod_expires and mod_headers, and you want to set the expiry on static resources, try putting this in your .htaccess file:

# Turn on Expires and set default to 0
ExpiresActive On
ExpiresDefault A0

# Set up caching on media files for 1 year (forever?)
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$">
ExpiresDefault A29030400
Header append Cache-Control "public"
</FilesMatch>

有关其他组合和更多示例,请参见:http://www.askapache.com/htaccess/speed-up-your-site-with-caching-and-cache-control.html

For other combinations and more examples see: http://www.askapache.com/htaccess/speed-up-your-site-with-caching-and-cache-control.html

这篇关于使用 PHP 和 Apache 设置 HTTP 过期标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆