移动端临时跳转应使用 return 302 https://m.example.com$request_uri,统一置于 listen 80 块中,禁用 UA 判断和 rewrite,确保路径参数完整、跳转链路干净且不干扰 SEO。

移动端网页临时跳转用 Nginx 配 302,核心是“只跳一次、不干扰 SEO、不污染协议”,不能套用永久跳转逻辑,也不能混入 UA 判断或多重 if 嵌套。
明确用 return 302,别用 rewrite redirect
直接返回状态码最干净,避免 rewrite 引发的隐式行为(比如多轮匹配、last/break 误用):
-
正确写法:
return 302 https://m.example.com$request_uri; -
不推荐:
rewrite ^/(.*)$ https://m.example.com/$1 redirect;—— redirect 是 rewrite 的 flag,语义弱、易与 permanent 混淆,且可能触发额外 location 匹配 - 所有跳转逻辑统一放在
listen 80的 server 块里,HTTPS 跳转走另一个块,避免端口和协议交叉干扰
跳转目标要带 $request_uri,保留路径和参数
用户访问 https://example.com/product?id=123,跳过去得是 https://m.example.com/product?id=123,不能丢参数或变成根路径:
- 用
$request_uri(含 query string),不是$uri(不含参数) - 如果后端依赖原始 host,可加
proxy_set_header Host $host;,但 302 跳转本身不经过 proxy,这步仅用于后续反向代理请求 - 不要写成
return 302 https://m.example.com/;—— 尾部斜杠 + 缺少 $request_uri 会强制归零路径
禁止在 80 端口块里做 UA 判断
HTTP 层不该决定“谁该跳”,否则桌面用户访问 http://example.com 可能被错误导向移动端,破坏兼容性:
- UA 判断应放在 HTTPS 的 server 块里(如 listen 443),且仅用于内容分发,不用于 302 跳转决策
- 真正需要区分端的场景,建议用独立域名(如 m.example.com / www.example.com),再用 DNS 或负载均衡分流,Nginx 只做纯协议/域名跳转
- 若必须按设备跳,应在应用层处理(如前端 JS 或后端判断),而非在 Nginx 用
$http_user_agent做 302
验证跳转链路是否干净
用 curl 测真实响应,防止出现双重 302 或协议错乱(比如 https → http:443):
-
curl -I http://example.com/test—— 看 Status 是否为302 Moved Temporarily - 检查
Location头是否唯一、协议正确、域名无 www 冗余(如https://m.example.com/test,不是https://www.m.example.com) - 若后端是 Spring Boot/RuoYi 等框架,确保已配置
proxy_set_header X-Forwarded-Proto $scheme;,否则它可能生成http://m.example.com:443这类错误地址


















