nginx做小程序外链跳转_Nginx通过UI实现移动端和电脑端自动双向跳转

场景

#

域名

描述

1

pc端

www.example.com

用于pc端访问官网

2

m.example.com

用于移动端访问

需求

在电脑端访问www.example.com和m.example.com都跳转到www.example.com

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

实现方法

为了实现跳转,可在页面中加入前端跳转代码JS对ua进行适配跳转。这种方式存在三个缺点:

a) 对用户:会加大由重定向的客户端造成的延迟;这是因为客户端需要先下载网页,接着解析并执行 JavaScript,然后才能触发重定向。301或302则不会有这个延迟。

b) 对搜索:爬虫也需要使用支持JS渲染的爬虫,才能发现此重定向。

c) 无法实现双向跳转或兼容性差:笔者尝试过多种公开代码进行测试,只能实现单向跳转,进行双向跳转时会造成死循环。

为了对用户和搜索引擎更友好,我们采取在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;

}

关于判断客户端UI,技术宅在很早之前就因为配置Nginx缓存用来区分移动端和PC端而说过, 具体大家可以查看以下文章!

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值