Random Index 模块自 Nginx 0.7.15 起内置源码中,需在 configure 阶段显式添加 --with-http_random_index_module 参数启用;启用后仅对以 / 结尾的 GET 目录请求生效,且忽略 index 指令。

Nginx 源码编译时启用 Random Index 模块,关键在于该模块是 Nginx 官方提供的 第三方模块(实际为 ngx_http_random_index_module),但默认不编译进主程序,需在 ./configure 阶段显式启用。
确认模块是否可用
Random Index 模块自 Nginx 0.7.15 起已内置在源码中(位于 src/http/modules/ngx_http_random_index_module.c),无需额外下载。只要使用较新版本的官方源码(如 1.20+、1.24+),该模块就存在,只是默认不启用。
编译时启用模块的方法
在执行 ./configure 时,添加 --with-http_random_index_module 参数:
- 进入解压后的 Nginx 源码目录(如
nginx-1.24.0/) - 运行完整 configure 命令(示例):
./configure --with-http_random_index_module --prefix=/usr/local/nginx - 后续照常执行:
make && sudo make install
验证是否启用成功
安装完成后,检查模块是否被编译进去:
- 运行
/usr/local/nginx/sbin/nginx -V 2>&1 | grep random,若输出中包含--with-http_random_index_module,说明已启用 - 或直接测试配置:在
location块中加入random_index on;,然后运行nginx -t;若无报错,且访问对应目录能随机返回一个文件(而非固定 index.html),即生效
注意事项
-
random_index on;只对GET请求且请求路径以/结尾(即目录索引)时生效,且要求目录下至少有两个文件(不含.和..) - 它与
index指令互斥——一旦启用random_index on,index将被忽略 - 该模块不支持正则匹配或过滤文件类型,仅对目录内所有普通文件做等概率随机选择


















