随机重定向用于a/b测试等场景,nginx可通过map+random模块或lua脚本实现加权跳转,next.js则在getserversideprops中按权重返回redirect对象。

当需要将用户随机分发到多个目标页面以实现A/B测试、灰度发布、负载分流或防爬策略时,random redirect page就成为关键配置手段。它不依赖固定路径映射,而是每次请求动态选择一个目标地址返回302响应,避免客户端缓存导致流量倾斜。
基于Nginx实现随机跳转
方法一:使用map + random模块(推荐)
确认Nginx已启用ngx_http_map_module和ngx_http_random_index_module——若未编译进内核,需重新configure添加--with-http_random_index_module。
在http块中定义随机映射:
map $random $target_url {
0.2 "https://a.example.com";
0.5 "https://b.example.com";
0.8 "https://c.example.com";
1.0 "https://d.example.com";
}
这一步必须放在server块之外,否则Nginx启动会报错【map指令只能位于http上下文】。
在server块中添加重定向逻辑:
location /random-redirect {
return 302 $target_url;
}
用Lua脚本控制跳转权重
第一步:确认OpenResty或Nginx已加载ngx_http_lua_module模块。
第二步:在location块内嵌入Lua代码:
location /rand {
content_by_lua_block {
local urls = {"https://page1.com", "https://page2.com", "https://page3.com"}
local weights = {0.4, 0.35, 0.25}
local sum = 0
for _, w in ipairs(weights) do sum = sum + w end
local rand = math.random() * sum
local acc = 0
for i, w in ipairs(weights) do
acc = acc + w
if rand ngx.redirect(urls[i], 302)
return
end
end
}
}
注意:math.random()默认种子为系统时间,若需更均匀分布,应在init_by_lua_block中调用math.randomseed(os.time())。
Next.js中服务端生成随机重定向
在pages目录下新建redirect.js文件:
export default function RedirectPage() {
return null;
}
添加getServerSideProps函数:
export async function getServerSideProps(context) {
const targets = [
{ url: '/test-a', weight: 0.6 },
{ url: '/test-b', weight: 0.3 },
{ url: '/maintenance', weight: 0.1 }
];
const rand = Math.random();
let acc = 0;
for (const t of targets) {
acc += t.weight;
if (rand return { redirect: { destination: t.url, permanent: false } };
}
}
return { redirect: { destination: '/', permanent: false } };
}
这一步必须返回redirect对象,不能用res.writeHead()手动写状态码,否则Next.js中间件会冲突导致500错误。











