Nginx入门到实践:适配 PC 或移动设备

2020-08-2617:59:53服务器及运维Comments1,553 views字数 833阅读模式

13. 适配 PC 或移动设备

根据用户设备不同返回不同样式的站点,以前经常使用的是纯前端的自适应布局,但无论是复杂性和易用性上面还是不如分开编写的好,比如我们常见的淘宝、京东......这些大型网站就都没有采用自适应,而是用分开制作的方式,根据用户请求的 user-agent 来判断是返回 PC 还是 H5 站点。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/yunwei/20159.html

首先在 /usr/share/nginx/html 文件夹下 mkdir 分别新建两个文件夹 PCmobilevim 编辑两个 index.html 随便写点内容。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/yunwei/20159.html

cd /usr/share/nginx/html
mkdir pc mobile
cd pc
vim index.html   # 随便写点比如 hello pc!
cd ../mobile
vim index.html   # 随便写点比如 hello mobile!
复制代码

然后和设置二级域名虚拟主机时候一样,去 /etc/nginx/conf.d 文件夹下新建一个配置文件 fe.sherlocked93.club.conf文章源自菜鸟学院-https://www.cainiaoxueyuan.com/yunwei/20159.html

# /etc/nginx/conf.d/fe.sherlocked93.club.conf

server {
  listen 80;
	server_name fe.sherlocked93.club;

	location / {
		root  /usr/share/nginx/html/pc;
    if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
      root /usr/share/nginx/html/mobile;
    }
		index index.html;
	}
}
复制代码

配置基本没什么不一样的,主要多了一个 if 语句,然后使用 $http_user_agent 全局变量来判断用户请求的 user-agent,指向不同的 root 路径,返回对应站点。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/yunwei/20159.html

在浏览器访问这个站点,然后 F12 中模拟使用手机访问:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/yunwei/20159.html

Nginx入门到实践:适配 PC 或移动设备

可以看到在模拟使用移动端访问的时候,Nginx 返回的站点变成了移动端对应的 html 了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/yunwei/20159.html

作者:SHERlocked93文章源自菜鸟学院-https://www.cainiaoxueyuan.com/yunwei/20159.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/yunwei/20159.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/yunwei/20159.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定