IT 相关 · 2018 年 12 月 5 日

Nginx 配置移动端和电脑端自动双向跳转

场景

域名 描述
pc 端 www.example.com 用于 pc 端访问官网
移动端 m.example.com 用于移动端访问

需求

在电脑端访问 www.example.comm.example.com 都跳转到 www.example.com
在移动端访问 www.example.comm.example.com 都跳转到 m.example.com

实现方法

为了实现跳转,可在页面中加入前端跳转代码 JS 对 ua 进行适配跳转。这种方式存在三个缺点:
a) 对用户:会加大由重定向的客户端造成的延迟;这是因为客户端需要先下载网页,接着解析并执行 JavaScript,然后才能触发重定向。 301 或 302 则不会有这个延迟。
b) 对搜索:爬虫也需要使用支持 JS 渲染的爬虫,才能发现此重定向。
c) 无法实现双向跳转或兼容性差:笔者尝试过多种公开代码进行测试,只能实现单向跳转,进行双向跳转时会造成死循环。

关于移动适配,百度的官方建议:
https://ziyuan.baidu.com/college/courseinfo?id=156

为了对用户和搜索引擎更友好,我们采取在 Nginx 进行跳转配置。

代码

电脑端:www.example.com

server {
      listen       80;
      server_name  www.example.com;

      #charset koi8-r;
      #access_log  logs/host.access.log  main;
    # 下面根据 user_agent 可以获取
     if ($http_host !~ "^www.example.com$") {
      rewrite  ^(.*)    http://www.example.com$1 permanent;
     }
     if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
      rewrite  ^(.*)    http://m.example.com$1 permanent;
     }
    location / {
            root     /home/build/rampage-home-front/dist/html;
            index  index.html index.htm;
     }

}

作用部分代码如下:

     if ($http_host !~ "^www.example.com$") {
      rewrite  ^(.*)    http://www.example.com$1 permanent;
     }
     if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
      rewrite  ^(.*)    http://m.example.com$1 permanent;
     }

手机端:m.example.com

server {
      listen       80;
      server_name  m.example.com;

      #charset koi8-r;
      #access_log  logs/host.access.log  main;
    #非移动端跳转到 www.example.com
     if ($http_user_agent !~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
      rewrite  ^(.*)    http://www.example.com$1 permanent;
     }

    location / {
        root     /home/build/rampage-mobile-front/dist;
        index  index.html index.htm;
      }
}

作用部分代码如下:

if ($http_user_agent !~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
      rewrite  ^(.*)    http://www.example.com$1 permanent;
     }

如果配置了 SSL 证书,需要在 443 端口同样配置。