织梦手机端和电脑端如何判断跳转
织梦站点通常使用 PC 模板 + 移动模板(m 子目录)的双端结构。让用户访问正确的端,是提升体验与百度移动端收录的关键。本文梳理几种主流判断跳转方式,并给出适配织梦的具体写法。
一、判断跳转的基本思路
核心是识别访问者 UA(User-Agent)或屏幕宽度,然后跳到对应的域名/目录:
- PC 访问 → 跳到
www.example.com - 移动访问 → 跳到
m.example.com或www.example.com/m/
建议同时使用“服务端 UA 判断 + 前端 JS 兜底”,兼顾首屏速度与误判容错。
二、JS 判断跳转(最常用)
在 PC 模板 /templets/default/header.htm 的 <head> 内加入:
<script>
(function(){
var ua=navigator.userAgent.toLowerCase();
var isMobile=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(ua);
if(isMobile && location.href.indexOf('/m/')===-1){
var murl=location.href.replace(location.host, location.host + '/m');
location.replace(murl);
}
})();
</script>
在移动模板 /m/header.htm 里反向判断:
<script>
(function(){
var ua=navigator.userAgent.toLowerCase();
var isMobile=/android|iphone|ipad|ipod|iemobile/i.test(ua);
if(!isMobile){
var pcurl=location.href.replace('/m/', '/');
location.replace(pcurl);
}
})();
</script>
location.replace 而非 location.href,避免在浏览器历史里留下跳转记录,用户按返回键不会陷入循环。三、PHP 服务端判断(织梦内置)
织梦自带 IsMobile() 判断函数,可在 /include/common.inc.php 之后调用。在模板顶部用原生 PHP:
<?php
if(!function_exists('IsMobile')){
function IsMobile(){
$ua=strtolower($_SERVER['HTTP_USER_AGENT']);
return preg_match('/(android|iphone|ipod|ipad|windows phone|ucweb|blackberry)/i', $ua);
}
}
if(IsMobile() && strpos($_SERVER['REQUEST_URI'],'/m/')===false){
Header("HTTP/1.1 302 Moved Temporarily");
Header("Location: /m".$_SERVER['REQUEST_URI']);
exit;
}
?>
服务端判断的好处是直接返回 302,不渲染 PC HTML,首屏更快,也避免被搜索引擎识别为“软 404”。
四、Nginx 层 UA 判断(推荐)
在宝塔/Nginx 站点配置的 server 块内加入:
set $mobile_rewrite 0;
if ($http_user_agent ~* "(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino") {
set $mobile_rewrite 1;
}
if ($mobile_rewrite=1) {
rewrite ^/(.*)$ http://m.example.com/$1 redirect;
}
Nginx 层判断性能最高,且对 SEO 友好,配合 rel="alternate" 标注更佳。
五、对搜索引擎的适配标注
百度移动适配要求在 PC 页 <head> 中声明对应关系:
<link rel="alternate" media="only screen and (max-width: 640px)" href="http://m.example.com{dede:field name='arcurl'/}" >
<link rel="canonical" href="http://www.example.com{dede:field name='arcurl'/}">
移动页反向声明 canonical 指向自身,并提交百度站长平台的“移动适配”规则。
六、常见问题
1. 跳转死循环
通常是 PC 和移动模板都加了跳转判断且条件互相覆盖。务必确认两边判断逻辑互斥,且只在 URI 不含 /m/ 时才跳。
2. 百度蜘蛛被抓到移动端
百度有 PC 蜘蛛和移动蜘蛛两套 UA,判断时不要把 Baiduspider 一律当移动端。建议 UA 正则只匹配移动设备关键词,不依赖“spider”字样。
3. HTTPS 跳转后丢失参数
跳转时务必带上 $_SERVER['REQUEST_URI'] 或 location.search + location.hash,否则分页/锚点会丢失。
七、注意事项
- 移动模板目录
/m/要在织梦后台“系统 - 站点设置”里正确配置 mobile 模板路径; - JS 跳转要在 DOM 渲染前执行,否则会闪一下 PC 页面;
- 双端模板都要有独立 sitemap,分别提交;
- 避免用
display:none隐藏 PC 内容冒充移动页,会被百度降权。
判断跳转是织梦移动化的第一步,跑通后建议进一步用响应式或独立移动模板优化移动端体验,并结合百度搜索资源平台的数据反馈持续调整适配规则,让 PC 与移动流量都能稳定落地到正确页面。