nginx下判断移动端和pc端网页自动跳转的方法
场景,示例域名描述
pc端:www.wendabaike.com(用于pc端访问官网)
移动端:m.wendabaike.com(用于移动端访问)
现在的需求是这样:
在pc端访问www.wendabaike.com和m.wendabaike.com都跳转到www.wendabaike.com
而在手机移动端访问www.wendabaike.com和m.wendabaike.com都跳转到m.wendabaike.com
pc端配置:www.wendabaike.com
server {
listen 80;
server_name www.wendabaike.com;
#charset koi8-r;
#access_log logs/host.access.log main;
# 下面根据user_agent可以获取
if ($http_host !~ "^www.wendabaike.com$") {
rewrite ^(.*) http://www.wendabaike.com$1 permanent;
}
if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
rewrite ^(.*) http://m.wendabaike.com$1 permanent;
}
location / {
root /home/build/rampage-home-front/dist/html;
index index.html index.htm;
}
}
作用部分代码如下:
if ($http_host !~ "^www.wendabaike.com$") {
rewrite ^(.*) http://www.wendabaike.com$1 permanent;
}
if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
rewrite ^(.*) http://m.wendabaike.com$1 permanent;
}
移动端配置:m.wendabaike.com
server {
listen 80;
server_name m.wendabaike.com;
#charset koi8-r;
#access_log logs/host.access.log main;
#非移动端跳转到 www.wendabaike.com
if ($http_user_agent !~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
rewrite ^(.*) http://www.wendabaike.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.wendabaike.com$1 permanent;
}
至此完成了相关配置
作者:阿亮私语