跨站临时跳转应使用 return 302 + 完整 url(含协议和域名),如 return 302 https://other-site.com/path?arg=1;若仅写 /path 则为站内跳转,非跨站;需配合 location 精确匹配或前缀匹配,并注意变量引用需加双引号、避免循环跳转及响应头问题。

跨站临时跳转用 Nginx 的 302 重定向,核心是 location 匹配 + return 302 + 完整目标 URL,且必须带协议和域名,否则会变成站内相对跳转。
确保跳转地址是完整 URL
302 是临时重定向,浏览器不会缓存,但 Nginx 不会自动补全协议或域名。如果只写路径(如 /new-path),它会跳到当前域名下的该路径,不是跨站。
- ✅ 正确写法:
return 302 https://other-site.com/path?arg=1; - ❌ 错误写法:
return 302 /path;(仍是本站) - ⚠️ 注意:URL 中若有变量(如 $arg_x),需用双引号包裹,避免空格或特殊字符解析出错
按条件匹配做跳转(常见场景)
比如只对特定路径、参数或来源域名做跨站跳转,可用 if 或更推荐的 location 块 + rewrite/return 组合:
- 按路径跳转:
location = /old-url { return 302 https://new.example.com/; } - 带参数透传:
location ^~ /legacy/ { return 302 https://api.newsite.com$uri?$args; } - 限制 Referer(谨慎用):
if ($http_referer ~* example\.old) { return 302 https://new.example.com/; }
避免循环跳转和响应头问题
跨站 302 后,浏览器发起新请求,目标站需能正常响应。Nginx 本身不代理,只发响应头,所以要注意:
- 确认目标 URL 可访问(建议 curl -I 测试 HTTP 状态码)
- 不要在跳转规则里混用
proxy_pass,那属于反向代理,不是 302 - 若需隐藏原始参数,用
$request_uri或手动拼接,避免$args带空值引发多余问号 - 如需兼容旧客户端,可加
add_header Cache-Control "no-store, no-cache";强制不缓存
验证配置是否生效
改完 nginx.conf 后必须重载,再用命令行快速验证:
- 执行
nginx -t检查语法 - 运行
nginx -s reload - 用
curl -I http://your-domain/old-path查看响应头中Location:是否为预期跨站地址 - 注意:浏览器可能缓存 302(尤其反复测试时),建议用无痕模式或加随机参数(如
?t=123)绕过











