Nginx 设置屏蔽PC端访问请求

in web with 0 comment

需求说明

接开发的需求:
1.屏蔽所有pc端的请求
2.安卓移动端不做限制,访问原链接
3.苹果移动设备跳转到指定的推广页面

Nginx配置

首先想到的就是根据user_agent去判断请求链接来自移动还是pc,pc直接返回404即可,iPhone做rewrite跳转。而安卓不需要做操作,折腾了一个多小时,开始被安卓绕住了,最终规则如下:

#假设跳转到baidu页面
if ($http_user_agent ~* "iPhone|ipad"){
     rewrite ^/(.*)$ http://www.baidu.com permanent;                      
}

#如果不是安卓也不是苹果,那就认为是PC端请求
if ($http_user_agent ~* "Android|iPhone|ipad"){                           
    return 404;            
}

如果是针对".apk"后缀的文件做如上操作,方法如下:

location ~ .*\.apk$ {

if ($http_user_agent ~* "iPhone|ipad"){
         rewrite ^/(.*)$ http://www.baidu.com permanent;                      
    }
if ($http_user_agent ~* "Android|iPhone|ipad"){                           
        return 404;            
    }
}

至此结束,是不是很简单呢。如果大家有更好的方法,欢迎留言讨论!

Responses