NGINX 用户标识模块 (ngx_http_userid_module) 完整配置与最佳实践指南
1. 模块概述
ngx_http_userid_module
用于在客户端和服务器之间设置和管理标识用户的 Cookie,以便在后续请求中识别同一客户端。该模块:
- 支持生成 Version 1 和 Version 2 Cookie,并能兼容 Apache 的 mod_uid 模块
- 通过内置变量
$uid_got
和$uid_set
记录接收到的和发送出去的客户端标识 - 可在
http
、server
或location
块中开启或关闭,并可只记录日志不设置 Cookie (Nginx)
2. 编译与兼容性
-
内置模块:自 NGINX 1.1.21 起,
ngx_http_userid_module
已包含在官方主线源码中,无需额外动态编译。 -
开启方式:默认情况下该模块处于
off
状态,可通过configure
时添加的选项来确认是否已启用:./configure --with-http_userid_module make && make install
-
兼容性:同样适用于 Tengine 等 NGINX 分支 (The Tengine Web Server)。
3. 主要指令详解
指令 | 语法 | 默认值 | 作用 | |||
---|---|---|---|---|---|---|
userid | on | v1 | log | off | off | 控制是否设置/记录 Cookie: - on :设置版本 2 Cookie 并记录- v1 :设置版本 1 Cookie 并记录- log :只记录接收 Cookie- off :禁用 | |||
userid_name | userid_name <name> | uid | 设置 Cookie 名称 | |||
userid_domain | `userid_domain <name | none>` | none | 定义 Cookie 域;none 则不指定 Domain | ||
userid_path | userid_path <path> | / | 定义 Cookie 路径 | |||
userid_expires | `userid_expires <time | max | off>` | off | 设置浏览器中 Cookie 保留时长: - <time> 比如 365d - max (2037-12-31)- off (会话结束时过期) | |
userid_p3p | `userid_p3p <string | none>` | none | 设置 P3P 响应头;none 则不发送 P3P | ||
userid_flags | `userid_flags <secure | httponly | samesite=… | …>` | off | 为 Cookie 添加附加标志,如 secure 、httponly 、samesite 等(1.19.3+) |
userid_mark | `userid_mark <letter | digit | => | off>` | off | 在重新发送标识时添加标记字符,用于保留标识不变同时更新 P3P 等 |
userid_service | userid_service <number> | 默认服务器 IP 后四段 | 为多机服务场景分配唯一服务号(Version 2 默认为 IP) |
示例:
http {userid on;userid_name uid;userid_domain example.com;userid_path /;userid_expires 365d;userid_p3p 'policyref="/w3c/p3p.xml", CP="CUR ADM OUR NOR STA NID"';userid_flags secure httponly samesite=strict; } ```:contentReference[oaicite:2]{index=2}
4. 内嵌变量
$uid_got
:客户端请求中携带的 Cookie 名称及标识值$uid_set
:响应中发送的 Cookie 名称及标识值$uid_reset
:若被设置为非空且非0
,则强制重置客户端标识;若为"log"
则在error_log
中记录重置信息 (Nginx)
可将这些变量添加到 log_format
中,以便在访问日志里追踪用户标识:
log_format userid_log '$remote_addr - $uid_got -> $uid_set ''"$request" $status';
access_log /var/log/nginx/userid_access.log userid_log;
5. 典型用例
-
精准流量分析
- 对重复访问的客户端进行去重统计,结合
$uid_got
分析真实独立访客数
- 对重复访问的客户端进行去重统计,结合
-
个性化内容投放
- 根据同一客户端的 Cookie,在多次会话间进行用户画像存储与推荐
-
防刷限频
- 结合
$uid_got
实现 IP+用户标识双重限频,提升防刷准确度
- 结合
6. 最佳实践与注意事项
- 隐私合规:若在 EU/US 等地区使用,需遵循 GDPR/CCPA,要告知用户并提供同意机制;
userid_p3p
可用于 IE 早期对 Third-Party Cookie 的容忍策略,但现代浏览器更多依赖SameSite
和用户同意。 - Cookie 标志:生产环境强烈建议添加
secure
(仅 HTTPS)和httponly
,并根据场景调整samesite
。 - 多服务部署:对多台 NGINX 反向代理/负载均衡节点,宜通过
userid_service
保证标识全局唯一,以免不同节点生成重复 ID。 - 性能影响:开启此模块对 NGINX 性能影响极小,但大量写入日志时要关注磁盘 I/O。
- 日志清理:若单独记录
userid_access.log
,需定期轮转(logrotate
)并清理老日志。
7. 小结
ngx_http_userid_module
提供了一种轻量级、无需后端介入的用户识别方案,适合于流量统计、限频防刷和简单的个性化场景。通过灵活的指令组合和日志变量,开发者可以在不改动后端逻辑的情况下,对客户端进行持续跟踪和分析。
希望这份指南能帮助你快速掌握并在项目中落地 ngx_http_userid_module
的配置与应用。