记一次通过Nginx为移动端和PC端返回不同页面内容且不影响的URL的处理方案

首先说下需求,由于WEB没写响应式页面,而是写了独立的PC和移动页面,导致必须要通过其他方式判断用户设备并且给出相应内容

初步的解决方案是

  • 通过前端JS跳转
  • 额外写一个index 隐藏跳转过程和url,根据用户UA加载移动端或者PC端代码
  • 通过服务端判断用户UA 返回不同内容

讨论结果是

  1. 通过前端JS跳转会导致移动端URL暴露,在用户做二次分享的时候体验也不好
  2. 额外写一个index来动态加载代码的方法我觉得挺棒的,但是前端太懒了不想写
  3. 通过Nginx判断UA 返回内容,并且保证URL不变

好吧那就开写

先交代服务器情况 /home/www/ 是根目录 PC代码在test里 移动端代码在 test/mobile里

最先用的 if 里嵌套 alias 的方法 代码如下(注意:这种代码是错误的)

location /test/ {
 
if ( $http_user_agent ~ "(iPhone)|(Android)" ){
        alias /home/www/test/mobile/;
}

但是Nginx提示这种语法不支持。。。。
报错内容

nginx: [emerg] "alias" directive is not allowed here in /etc/nginx/sites-enabled/default:49

关于if的各种坑,可以查看 https://xwsoul.com/posts/761?tdsourcetag=s_pctim_aiomsg
感觉写的还不错

然后咨询和讨论得到两种解决方法

  1. 通过 rewrite 和 location 做两次处理
  2. 通过 if 内嵌变量,然后把用alias+变量的方法间接处理

上代码

方案一

    location ~ ^/test(/.*) {
    set $way $1;
            if ( $http_user_agent ~ "(iPhone)|(Android)" ){
        rewrite ^ fuckurl$way;
    }
}

location fuckurl/ {
    internal;
    alias /home/www/test/mobile/;
}



方案二

location /test/ {
set $getdir "/home/www/test/";
            if ( $http_user_agent ~ "(iPhone)|(Android)" ){
        set $getdir "/home/www/test/mobile/";
    }
alias $getdir;
}

都实测过了,代码能用

标签: none

添加新评论