必须在 configure 阶段显式加入 --with-http_realip_module 参数才能启用 RealIP 模块;该模块不默认启用,需通过 nginx -V 检查是否已编译支持,启用后还需在配置中设置 set_real_ip_from 和 real_ip_header。

要在 Nginx 源码编译时启用 RealIP 模块,必须在 configure 阶段显式加入 --with-http_realip_module 参数。该模块不默认启用,即使其他常用模块(如 SSL、gzip)已开启,RealIP 仍需单独声明。
确认当前 Nginx 是否已支持 RealIP
执行以下命令检查:
nginx -V 2>&1 | grep -o with-http-realip-module
若输出含该字符串,说明已编译支持;若无输出,则需重新编译。
源码编译启用 RealIP 的关键步骤
- 进入 Nginx 源码目录(如 /tmp/nginx-1.20.2)
- 运行 configure 命令,务必包含 --with-http_realip_module,例如:
./configure --prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-http_realip_module
- 执行 make && make install 完成安装
- 验证:再次运行 nginx -V,确认输出中含 with-http-realip-module
注意事项
- 如果是在已有 Nginx 上追加模块(非全新安装),需用 nginx -V 查看原 configure 参数,必须完整复用原有参数,再额外添加 --with-http_realip_module,否则会丢失原有功能
- OpenResty 用户无需额外操作,RealIP 模块已默认内置
- 部分云厂商定制版 Nginx 可能禁用该模块,此时只能通过源码编译覆盖或替换二进制
配置生效前还需做两件事
- 在 nginx.conf 的 http 或 server 块中添加可信代理设置,如:
set_real_ip_from 192.168.0.0/16;
real_ip_header X-Forwarded-For; - 确保上游代理(如 CDN、LB)确实设置了 X-Forwarded-For 头,否则 RealIP 模块无数据可解析


















