最简洁可靠的测试域名跳转方案是使用Nginx的return 302指令,直接在server块中监听测试域名并返回302响应,避免rewrite解析,性能更优、逻辑更清晰;支持正则匹配多域名、HTTPS跳转及特定路径排除。

直接用 return 302 最简洁可靠,适合开发测试域名临时跳转到生产环境。
明确指定测试域名并跳转
在 Nginx 的 server 块中监听测试域名,直接返回 302 响应,不经过 rewrite 解析,性能更好、逻辑更清晰:
- 配置示例(监听
dev.example.com跳转到example.com):
listen 80;
server_name dev.example.com;
return 302 https://example.com$request_uri;
}
注意:$request_uri 会完整保留原始路径和查询参数,比如访问 dev.example.com/api/test?x=1 就会跳转到 https://example.com/api/test?x=1。
支持多个测试域名统一跳转
如果有多套测试域名(如 dev.example.com、test.example.com、staging.example.com),可用正则匹配 server_name:
- 配置写法:
listen 80;
server_name ~^(dev|test|staging)\.example\.com$;
return 302 https://example.com$request_uri;
}
这样所有匹配的子域都会自动 302 跳转,无需重复写多个 server 块。
HTTPS 测试域名也跳转到生产 HTTPS
若测试域名本身也配了 HTTPS(例如用于本地联调),需额外加一个监听 443 的 server 块:
- 必须提供有效证书(哪怕自签名),否则浏览器会拦截连接;
- 配置核心仍是
return 302,协议可保持一致或强制升级:
listen 443 ssl;
server_name dev.example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
return 302 https://example.com$request_uri;
}
避免误跳转:排除特定路径
有时需要让某些调试路径(如 /health 或 /debug)不跳转,留在测试环境处理:
- 用
location拦截并终止跳转:
listen 80;
server_name dev.example.com;
location = /health {
return 200 "OK";
add_header Content-Type text/plain;
}
location / {
return 302 https://example.com$request_uri;
}
}
这样访问 dev.example.com/health 直接返回 200,其他所有请求都 302 跳转。


















