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

2019-09-27  本文已影响0人  石_a41c

原文出处 https://shiwenyuan.github.io/post/ck05d728k0000fys6pin2i1eu.html

场景

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

需求

在移动端访问www.phpblog.com.cn和m.phpblog.com.cn都跳转到m.phpblog.com.cn

实现方案

判断客户端的设备类型
要想让网站适配PC和手机设备,首先要能做出准确的判断。HTTP请求的Header中的User-Agent可以区分客户端的浏览器类型,可以通过User-Agent来判断客户端的设备。

nginx原始配置

pc配置

server {
    listen       80;
    server_name  www.phpblog.com.cn;
    location / {
        root   www;
        index  index.html index.htm;
    }
}

移动端配置

server {
    listen       80;
    server_name  m.phpblog.com.cn;
    location / {
        root   m;
        index  index.html index.htm;
    }
}

m/index.html

image.png

www/index.html

image.png

nginx修改后配置

pc配置

server {
    listen       80;
    server_name  www.phpblog.com.cn;
    if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
            rewrite  ^(.*)    http://m.phpblog.com.cn$1 permanent;
        }
    location / {
        root   www;
        index  index.html index.htm;
    }
}

移动端配置

server {
    listen       80;
    server_name  m.phpblog.com.cn;
    if ($http_user_agent !~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
            rewrite  ^(.*)    http://www.phpblog.com.cn$1 permanent;
        }
    location / {
        root   m;
        index  index.html index.htm;
    }
}

此时在pc访问m.phpblog.com.cn


image.png
可以看到有两次http请求第一次请求m.phpblog.com.cn发生了一次重定向 ,重定向到到了www.phpblog.com.cn

此时在pc访问www.phpblog.com.cn

image.png
可以看到有一次http请求第一次请求

此时在移动端访问m.phpblog.com.cn


image.png
可以看到有一次http请求第一次请求

此时在移动端访问www.phpblog.com.cn

image.png
可以看到有两次http请求第一次请求www.phpblog.com.cn发生了一次重定向,,重定向到到了 m.phpblog.com.cn

原理

nginx 利用每次http请求过来的浏览器ua来区分是移动端还是pc,然后做相应的跳转

相关文档

百度的官方建议
国外开源的通过User-Agent区分PC和手机的解决方案

上一篇下一篇

猜你喜欢

热点阅读