本文使用「署名 4.0 国际 (CC BY 4.0)」许可协议,欢迎转载、或重新修改使用,但需要注明来源。 [署名 4.0 国际 (CC BY 4.0)](https://creativecommons.org/licenses/by/4.0/deed.zh) 本文作者: 苏洋 创建时间: 2011年02月03日 统计字数: 1141字 阅读时间: 3分钟阅读 本文链接: https://soulteary.com/2011/02/03/%E6%B5%85%E8%B0%88%E7%BD%91%E7%AB%99%E8%AF%B7%E6%B1%82%E5%92%8C%E7%BC%93%E5%AD%98%E4%BC%98%E5%8C%96%E4%B9%8B%E4%BA%8C.html ----- # 浅谈网站请求和缓存优化之二 今天果然有点忙碌,先发一下代码吧。 首先图片最优的输出模式,定然是缩略图,那么选择一款好的开源缩略脚本,就是我们要做的了。 下面是一款不错的缩略脚本timthumb,链接如下。 http://code.google.com/p/timthumb/ 找到源文件内发送HEADER信息的地方,有2处 ```php header ('Content-type: ' . $mime_type); ``` 适当修改下 ```php $cache_file_name = NULL; header ('Content-Type: ' . $mime_type); header ('Accept-Ranges: bytes'); header ('Last-Modified: ' . $gmdate_mod); header ('Content-Length: ' . $fileSize); header ('Cache-Control: max-age=315360000'); //header ('Expires: ' . $gmdate_mod); header ('Expires: Wed, 27 Jan 2021 11:01:17 GMT'); ``` 如果使用了子域名,请注意修改函数cleanSource和get_document_root的字串处理。 然后定义一下apache的htaccess即可。 ```apache RewriteEngine On RewriteRule ^/?image$ image\.php [L] RewriteRule ^image-(\d+)\.jpg$ image\.php?w=$1 [L] RewriteRule ^image-(\d+)\.jpg$ image\.php?h=$1 [L] RewriteRule ^image-(\d+)x(\d+)\.jpg$ image\.php?w=$1&h=$2 [L] RewriteRule ^image-(\d+)x(\d+)-(\d+)\.jpg$ image\.php?w=$1&h=$2&zc=$3 [L] RewriteRule ^image-(\d+)x(\d+)-(\d+)-((?i)[^'""\s>]+(?:\.jpg|gif|png|bmp))\.jpg$ image\.php?w=$1&h=$2&zc=$3&src=$4 [L] ``` 这样子,原本类似 http://yoursite/path/image.php?h=171&w=171&zc=171&src=yourpic.jpg 变可以直接静态化为http://yoursite/path/image-171x171-171-yourpic.jpg.jpg 最后多一个.jpg是为了防止文件名空,某些高端浏览器不适应. 先写到这里,过年咯~