从 http 1.1 规范开始(RFC 2616 https://www.ietf.org/rfc/rfc2616.txt) 第 14.9.1 章
private
Indicates that all or part of the response message is intended for
a single user and MUST NOT be cached by a shared cache. This
allows an origin server to state that the specified parts of the
标头设置 Cache-Control “private, ...” 就可以了。
不需要 Expires 标头。缓存控制:最大年龄覆盖
过期字段。请参阅 RFC 部分:14.21
您应该根据您提供的内容发送不同的缓存标头。
以下示例适用于在 /static 中提供静态内容并为登录用户提供变化内容的网站。登录的用户通过会话 cookie 的存在来识别:MYSESSID。
- 默认允许 5 分钟公共缓存
- 允许对静态文件进行 365 天公共缓存
- 允许登录用户 5 分钟私人缓存
- 拒绝 /dynamic/* 处的缓存
RewriteEngine On
# Flag files in /static as STATIC
RewriteRule ^static - [E=STATIC:1]
# Flag requests by logged in users as PRIVATE
# Users are identified by presence of MYSESSID cookie
# Ignores files in: /static
RewriteCond %{HTTP_COOKIE} MYSESSID
RewriteCond %{REQUEST_URI} !^/static
RewriteRule ^ - [E=PRIVATE:1]
# Tell proxy servers that contents not in /static vary based on the given cookies
RewriteCond %{REQUEST_URI} !^/static
RewriteRule ^ - [E=VARY:1]
# Flag requests to /dynamic as NO_CACHE
RewriteRule ^dynamic - [E=NO_CACHE:1]
## Default Cache-Control
# Per default, any content is public and 5min cacheable
Header set Cache-Control "public, max-age=300"
## Static Files
# Static files are public and 365d cacheable.
Header set Cache-Control "public, max-age=31536000" env=STATIC
# Reset age, indicates objects as fresh
Header set Age 0 env=STATIC
## Private responses
# private. Allow 5min caching
Header set Cache-Control "private, max-age=300" env=PRIVATE
## Deny caching
Header set Cache-Control "private, max-age=0, no-cache, no-store, must-revalidate" env=NO_CACHE
## Vary rules
Header append Vary: Cookie env=VARY