Nginx 编译启用 User ID 模块需在 configure 时添加 --with-http_userid_module 参数,该模块为官方内置但默认不启用;确认源码中存在 src/http/modules/ngx_http_userid_module.c 即可;启用后通过 nginx.conf 配置 userid on; 等指令生效,并可用 $uid_got、$uid_set 变量。

Nginx 源码编译时启用 User ID 模块(即 ngx_http_userid_module),不需要额外下载第三方模块,因为它属于 Nginx 官方内置模块,但默认**不自动启用**,需在 ./configure 阶段显式开启。
确认模块是否可用
该模块从 Nginx 0.6.7 起就已集成在源码中,只要使用较新的稳定版(如 1.20+、1.24+)均包含。检查源码目录下的 src/http/modules/ngx_http_userid_module.c 存在即可确认。
编译时启用 User ID 模块
运行 ./configure 时添加 --with-http_userid_module 参数:
- 进入解压后的 Nginx 源码目录(如
nginx-1.24.0/) - 执行完整 configure 命令示例(含常用基础选项):
./configure \ --prefix=/usr/local/nginx \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_gzip_static_module \ --with-http_userid_module # ← 关键:启用 User ID 模块
- 之后照常执行
make && sudo make install - 安装完成后,可通过
nginx -V 2>&1 | grep userid验证是否已编译进内核(输出中出现--with-http_userid_module即成功)
配置并使用 User ID 功能
模块启用后,还需在 nginx.conf 中配置指令才能生效:
- 在
http、server或location块中添加:
userid on; userid_name UID; # 可选:设置 Cookie 名称,默认为 uid userid_domain example.com; # 可选:指定 Cookie 的 domain userid_path /; # 可选:指定 Cookie 的 path userid_expires max; # 可选:设置过期策略(max / 1d / off 等)
- Nginx 会自动为首次访问的客户端生成唯一标识(base64 编码的 128 位随机数),存入 Cookie(如
UID=00000123456789ab),后续请求复用该值 - 可通过
$uid_got和$uid_set变量在日志或响应头中引用(例如写入 access_log 或添加add_header X-UID $uid_got;)
注意事项
- 该模块仅生成/读取 Cookie,不提供用户认证或会话管理能力,不可替代 auth 或 JWT
- 若启用 HTTPS,建议配合
userid_secure on;强制 Cookie 使用 Secure 属性 - Cookie 默认无 HttpOnly 标志,如需增强安全性,需借助
more_set_headers(需第三方 headers-more 模块)或 OpenResty - 不支持子域名自动共享(除非显式配置
userid_domain .example.com;)


















