使用 PHP 和 Apache 设置 HTTP 过期标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1036941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setup HTTP expires headers using PHP and Apache
提问by Tom
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 + Apache 中设置过期标头?我目前正在使用 auto_prepend 来提供 gzip 压缩的资源,但我也想最大化 HTTP 缓存。
How can I set these up?
我该如何设置这些?
回答by brianegge
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.
有两种方法可以做到这一点。第一个是在你的 php 代码中指定标题。如果您想以编程方式调整到期时间,这很好。例如,wiki 可以为不经常编辑的页面设置更长的过期时间。
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60))); // 1 hour
Your second choice is to create an .htaccessfile 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_headersor 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:
您的第二个选择是创建一个.htaccess文件或修改您的 httpd 配置。在共享主机环境中,修改 .htaccess 文件是很常见的。为此,您需要知道您的服务器是否支持mod_expires、mod_headers或两者。最简单的方法就是反复试验,但某些 Apache 服务器配置为允许您通过 /server-info 页面查看此信息。如果您的服务器同时具有 mod_expires 和 mod_headers,并且您想在静态资源上设置到期时间,请尝试将其放入您的 .htaccess 文件中:
# 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>
For other combinations and more examples see: http://www.askapache.com/htaccess/speed-up-your-site-with-caching-and-cache-control.html
有关其他组合和更多示例,请参见:http: //www.askapache.com/htaccess/speed-up-your-site-with-caching-and-cache-control.html
回答by middus
This Apache module might be of help: http://httpd.apache.org/docs/2.0/mod/mod_expires.html
这个 Apache 模块可能有帮助:http: //httpd.apache.org/docs/2.0/mod/mod_expires.html
回答by acemtp
Did you try something like?
你尝试过类似的东西吗?
<?php
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
?>

