Nginx根据不同的UA显示不同的页面
Yakim Zhang

最近做了一个记录时间的 WebApp,只在手机端进行了适配,PC 上访问网站会变形,未来也不打算适配 PC 端,所以在 PC 使用 iframe 显示移动网页,一劳永逸。

要完成这个任务,首先需要新建一个 PC 端的页面,然后配置 Nginx 根据不同 UA 显示不同页面。

需求:

  1. 移动端访问时,显示 index.html
  2. PC 端访问时,显示 index.htm

1. 设计 PC 端页面 index.htm

  1. head 中删除视口设定(<meta name=”viewport” )
  2. body 中增加 iframe
1
2
3
4
5
6
7
8
9
<div class="iframe-wrap">
<iframe
id="frameDetail"
class="iframe"
src="http://localhost:3000/"
onload="setIframe()"
>
</iframe>
</div>
  1. 设置 iframe 样式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<style>
.body {
overflow: hidden;
}

.iframe-wrap {
overflow: hidden;
width: 390px;
height: 844px;
text-align: center;
margin-right: auto;
margin-left: auto;
}

.iframe {
width: 100%;
height: 100%;
transform: scale(0.88, 0.88);
overflow: auto;
}
</style>
  1. 用 JS 动态控制 iframe 尺寸,适配不同分辨率
1
2
3
4
5
6
7
8
9
<script>
function setIframe() {
let iframe = document.querySelector(".iframe-wrap");
let height = parseInt(screen.availHeight) - 250;
let width = height * 0.462;
iframe.style.height = height + "px";
iframe.style.width = width + "px";
}
</script>

2. nginx 配置

这个配置很不友好,需要很仔细,少个空格都会有问题。

思路:在原来的 location 中,根据 UA 信息动态设置 index 和 try_files

  1. 判断 UA

下面代码中,定义 2 个变量 isPcShow 和 rootulr

  • isPcShow:默认为 0,用来标记是否显示 PC 网页
  • rootulr:默认为 /index.html(移动网页)

因为 nginx 的 IF 语句不支持 else,所以只能借助标记 isPcShow 通过多个 if 语句来实现。

  1. 当 ua 不等于移动设备时,设置 isPcShow 01
  2. 当请求的参数中 mobile 不等于 1 时,设置 isPcShow 011 (因为 PC 的网页通过 iframe 嵌套来移动网页,所以 iframe 中的 url 要标识为移动,按照移动端来显示)

修改 index.htm

  1. 如果 isPcShow 等于 011,代表此时要显示 PC 网页(index.htm)
1
2
3
4
5
6
7
8
9
10
11
12
13
   set $isPcShow "0";
set $rootulr /index.html;
if ($http_user_agent !~* "(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino" ) {
set $isPcShow "${isPcShow}1";
}

if ( $args != mobile=1 ) {
set $isPcShow "${isPcShow}1";
}

if ( $isPcShow = "011" ) {
set $rootulr /index.htm;
}
  1. 动态设置 index 和 try_files
1
2
3
4
5
6

location / {
root /home/www/yktime/build;
index $rootulr;
try_files $uri $rootulr;
}

配置完成后,重置 nginx 就可以生效了。

此配置容易遗漏的点是:将 iframe 中 src 的 url 标识为移动端。