在 nginx 中配置接口实时数据绕过缓存,核心做法是修改 `proxy_cache` 的匹配规则,利用 `map` 指令根据请求 uri 或参数动态决定缓存状态。具体而言,定义一个变量(如 `$bypass_cache`),当请求命中特定路径(如 `/api/realtime`)时将其设为 1,否则为 0;随后在 `location` 块中使用 `proxy_cache_bypass $bypass_cache;` 和 `proxy_no_cache $bypass_cache;` 指令。这样,nginx 在收到指定接口的请求时,会直接向后端服务器发起新请求并返回最新数据,而不从本地缓存中读取。

如何根据 URI 路径区分缓存与实时请求
通过 `map` 指令可以建立 URI 到缓存开关的映射关系。对于常规页面请求,保持默认缓存行为;对于以 `/api/` 开头的实时数据接口,强制关闭缓存。这种配置方式简单直接,适用于大多数基于 URL 路径隔离的场景。

http {
# 定义缓存映射:默认不绕过,若 URI 包含 /api/realtime 则绕过
map $request_uri $bypass_cache {
default 0;
~^/api/realtime 1;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
# 启用缓存
proxy_cache my_cache;
# 如果 $bypass_cache 为 1,则跳过缓存读取
proxy_cache_bypass $bypass_cache;
# 如果 $bypass_cache 为 1,则不生成新的缓存文件
proxy_no_cache $bypass_cache;
}
}
}
上述配置中,`~^/api/realtime 1;` 使用正则表达式匹配。当用户访问 `/api/realtime/data` 时,`$bypass_cache` 变为 1,触发 `proxy_cache_bypass` 和 `proxy_no_cache`,确保每次请求都向后端获取最新数据。其他路径如 `/index.html` 则正常走缓存流程。
如何处理带参数的动态查询接口
有时实时数据接口可能带有查询参数,或者需要更精细的控制,例如排除特定 GET 参数。此时可以在 `map` 中结合 `$args` 变量进行判断。如果请求中包含 `?refresh=true` 参数,则视为实时请求,绕过缓存。这种方法允许前端通过添加特定参数来主动刷新数据,而无需改变 URL 结构。

http {
# 定义缓存映射:检查是否包含 refresh=true 参数
map $args $bypass_cache {
default 0;
~refresh=true 1;
}
server {
listen 80;
server_name example.com;
location /api/data {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_bypass $bypass_cache;
proxy_no_cache $bypass_cache;
}
}
}
在此示例中,访问 `/api/data?id=1` 会使用缓存,因为 `$args` 不包含 `refresh=true`。但访问 `/api/data?id=1&refresh=true` 时,`$bypass_cache` 为 1,Nginx 将直接向后端发起请求并返回结果,且不保存该响应到缓存中。这为需要手动刷新的场景提供了灵活的控制手段。
基于 Cookie 的个性化实时数据绕过
某些场景下,实时性要求与用户身份相关,例如管理员后台的数据必须实时显示。可以通过检查请求头中的 Cookie 来实现。定义一个 `map` 规则,当 Cookie 中包含 `admin_session` 时,设置 `$bypass_cache` 为 1。这样,只有携带特定 Cookie 的请求才会绕过缓存,普通用户依然享受缓存带来的性能提升。
http {
# 定义缓存映射:检查 Cookie 中是否包含 admin_session
map $http_cookie $bypass_cache {
default 0;
~*"admin_session" 1;
}
server {
listen 80;
server_name example.com;
location /admin/dashboard {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_bypass $bypass_cache;
proxy_no_cache $bypass_cache;
}
}
}
该配置确保了普通用户访问 `/admin/dashboard` 时,Nginx 会返回缓存的页面,减轻后端压力。而当管理员登录并携带 `admin_session` Cookie 时,请求将被直接转发至后端,获取最新的仪表盘数据。这种方式结合了性能优化与数据实时性的需求,适用于复杂的 Web 应用架构。











