Lighttpd:设置缓存控制:用于缓存目的的公共,最大年龄报头
如何使用Cache-Control头字段来指定所有缓存机制(例如代理服务器和浏览器)必须遵循的指令。
这将有助于减少lighttpd Web服务器服务的静态资产的延迟和网络流量。
如何在Unix之类的操作系统下使用Lighttpd Web服务器设置Cache-Control:public,max-age = SEC?
您可以使用lighttpd Web服务器发送以下以及许多其他类型的缓存控制标头:
public:强制缓存所有静态资产,即使它们通常是不可缓存的。
max-age=number-of-seconds:指定表示被认为是新鲜的最长时间。
must-revalidate:强制缓存服从您提供给他们的关于对象的任何新鲜度信息。
proxy-revalidate:与must-revalidate相同,除了它仅适用于代理缓存。
以上所有指令均会影响以下Web缓存:
- 您的网络浏览器,例如Firefox等。
- 网关和CDN网络,例如Cloudfront,Akamai等。
- 代理服务器和反向代理服务器,例如squid,nginx等。
示例:mod_expire和mod_setenv
mod_expire用于在Lighttpd Web服务器下的HTTP/1.0和HTTP/1.1消息的响应标头中设置Expire和Cache-Control:max-age标头。
mod_setenv模块允许影响生成外部应用程序的环境以及服务器发送给客户端的响应头。
编辑lighttpd.conf文件,执行:
# vi lighttpd.conf
激活mod_expire和mod_setenv:
server.modules = (
"mod_expire",
"mod_setenv",
"mod_redirect",
"mod_rewrite",
"mod_compress",
"mod_access",
"mod_auth",
"mod_fastcgi",
"mod_secdownload",
"mod_accesslog",
"mod_geoip"
)
警告!众所周知,由于模块的加载顺序不正确,mod_expire可能无法正常工作。
您必须在mod_fastcgi之前加载mod_expier。
在所有其他模块之前加载mod_expire是安全的。
例如,默认情况下,使存储在/images /中的所有镜像在访问后1个月后过期:
expire.url = ( "/images/" - "access plus 1 month" )
语法如下:
<access|modification> plus <number> <years|months|days|hours|minutes|seconds>
要使存储在server1.theitroad.local子域上的所有镜像在被访问后1000天失效,默认情况下:
$HTTP["url"] =~ "^/" {
expire.url = ( "" - "access 1000 days" )
}
要将公共标头添加到HTTP请求,请执行:
setenv.add-response-header += (
"Cache-Control" - "public"
)
要将public和必须重新验证都添加到HTTP请求,请执行:
setenv.add-response-header += (
"Cache-Control" - "public, must-revalidate"
)
配置参考
### config for static assets by theitroad for theitroad.local ###
$HTTP["host"] == "s0.theitroad.org"{
server.document-root = "/var/www/static-files"
accesslog.filename = "/var/log/lighttpd/s0.theitroad.org.log"
$HTTP["url"] =~ "^/" {
expire.url = ( "" - "access 5000 days" )
}
setenv.add-response-header += (
"Cache-Control" - "public, must-revalidate, proxy-revalidate"
)
}
保存并关闭文件。
重新加载或重新启动lighttpd Web服务器:
# service lighttpd restart
或者
# service lighttpd reload
如何查看和测试HTTP标头?
语法为:
curl -I http://static.example.com/images/file.png curl -I http://www.example.com/test.html
在此示例中,检查名为http://www.theitroad.local/media/images/category/old/light_logo.png的URL的HTTP资源,以了解它们将如何与Web缓存交互:
curl -I http://s0.theitroad.org/images/category/old/light_logo.png
输出示例:
HTTP/1.0 200 OK Content-Type: image/png Content-Length: 8852 Connection: keep-alive Server: nginx Date: Fri, 09 Nov 2012 10:06:32 GMT X-Whom: l3-com-cyber Cache-Control: public, must-revalidate, proxy-revalidate, max-age=432000000 Expires: Sun, 19 Jul 2026 10:06:32 GMT Accept-Ranges: bytes ETag: "732144214" Last-Modified: Wed, 14 Jan 2009 18:47:39 GMT Age: 15 X-Cache: Hit from cloudfront

