You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移动端自动跳转至m.example.com子域名失败问题求助

解决方案:移动设备自动跳转至子域名

你之前的JS跳转出错,核心原因是用了相对路径——浏览器会把m.example.com当成当前域名下的子路径,所以才会出现example.com/m.example.com的错误跳转。下面给你几种靠谱的解决方法:

一、修正JavaScript方案

把跳转目标改成完整的绝对URL,同时优化移动设备判断逻辑,避免循环跳转:

// 检测移动设备+避免循环跳转
const isMobileDevice = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || screen.width <= 699;
if (isMobileDevice && window.location.hostname !== 'm.example.com') {
    window.location.href = 'https://m.example.com';
}
  • 加https://前缀让浏览器识别为独立域名
  • 同时检测User Agent和屏幕宽度,覆盖更多移动设备场景
  • 判断当前域名不是m.example.com,防止无限循环跳转

二、PHP服务器端跳转方案(推荐)

服务器端跳转不受客户端JS禁用影响,体验更稳定。在主站首页index.php的最顶部(输出任何HTML内容之前)添加代码:

<?php
// 识别移动设备User Agent
$isMobile = preg_match('/(android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini)/i', $_SERVER['HTTP_USER_AGENT']);
// 获取当前访问域名
$currentHost = $_SERVER['HTTP_HOST'];

// 满足条件则跳转
if ($isMobile && $currentHost !== 'm.example.com') {
    header('Location: https://m.example.com');
    exit;
}
?>

三、.htaccess配置方案(Apache服务器适用)

如果你的服务器支持Apache的mod_rewrite模块,可以直接通过配置文件实现跳转,无需修改代码:

RewriteEngine On
# 排除移动子域名本身,避免循环跳转
RewriteCond %{HTTP_HOST} !^m\.example\.com$ [NC]
# 匹配移动设备的User Agent
RewriteCond %{HTTP_USER_AGENT} (android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini) [NC]
# 跳转至移动子域名,同时保留原访问路径
RewriteRule ^(.*)$ https://m.example.com/$1 [R=302,L]
  • R=302是临时跳转,后续确认不需要调整时可以改成R=301永久跳转
  • $1会把原访问路径带过去(比如example.com/about会跳转到m.example.com/about)

内容的提问来源于stack exchange,提问作者Erik den Boer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:57:44