移动端访问自动引导到触屏版需在HTTPS的server块中用return 302跳转,基于UA正则匹配移动设备并携带完整$request_uri;HTTP 80端口仅用return 301无差别升级协议,不参与设备判断。
移动端访问自动引导到触屏版,Nginx 必须用 return 302 实现临时跳转,且 UA 判断只能放在 HTTPS 的 server 块中、location 外层;HTTP(80 端口)只做协议升级,不参与设备识别。
所有移动端逻辑必须在 listen 443 ssl 的 server 块里完成,不能写在 80 端口或 location 内。这样可确保 UA 已解密、判断准确,也避免 HTTP 层误判桌面用户。
$http_user_agent ~* "(Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini)"
return 302 https://m.example.com$request_uri;
if ($http_user_agent ~* "..." && $arg_desktop != "1") { ... }
80 端口的配置仅负责把所有请求无差别升为 HTTPS,不涉及任何 UA 判断或域名跳转。
return 301 https://$host$request_uri;,保留原始 host 和完整 URI跳转生效的前提是基础环境可靠,几个硬性要求必须满足:
$request_uri(含 query string),不用 $uri 或硬编码路径,否则 ?id=123 这类参数会丢失set $real_scheme $scheme; 并在 proxy_set_header 中设 X-Forwarded-Proto $real_scheme;
上线前用命令行快速确认行为符合预期:
curl -I http://www.example.com/product?id=123:应返回 301 → 再对 HTTPS 地址测试,确认第二跳是 302 且 Location 指向 https://m.example.com/product?id=123