虽然响应式页面能够做到样式随着屏幕的变化保持一致,但对于移动端和 PC 端两个截然不同的体系来说,更好的用户体验无疑是为两者分别准备一套代码。也就是说,如果一个网站做了这样的设备适配,那么用户在移动端访问到的就是移动端的页面,在 PC 端访问到的就是 PC 端的页面。我们可以在 Nginx 服务器的 conf.d 文件中进行配置,以根据设备类型的不同来做页面的跳转。
一、不同域名的跳转 当一个项目的移动端和 PC 端页面是经由不同团队搭建时,所使用的框架、路由和域名都有可能不同。幸好,我们可以通过 rewrite 来灵活地将其进行动态更改。
假设开发的网站名为 mohui.com,存在首页、公益项目、新闻三种栏目。移动端域名为 m.b.mohui.com,栏目对应的路径分别为 /、/commonweal、/info;pc 端域名为 mc.b.mohui.com,栏目对应的路径分别为 /home.html、/gongyi.html、/news.html。这里需要根据设备类型,来使其一一对映并实现动态跳转。
1. 移动端配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 # 移动端配置 server { listen 80; server_name m.b.mohui.com; root /data/code/cms/mohui-web; autoindex on; index index.html home_page.html; # 如果设备类型不属于移动端,则跳转到pc端的域名。其中.*是指路径名(不带/)。加上括号表明是可获取的参数,后面的$1是获取的第一个参数。例如,m.b.mohui.com/info在pc端会跳到mc.b.mohui.com/info.html。当然这个域名是错误的,应该把info改成news才能在pc端访问,这可以在pc端中配置。 if ($http_user_agent !~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) { rewrite ^(.*) http://mc.b.mohui.com/$1.html permanent; } # 当url以/xxx结尾时,会将整个url进行修改重写。例如,当在移动端浏览器输入m.b.mohui.com/news时,会将url重写为m.b.mohui.com/info。 rewrite ^/home$ http://m.b.mohui.com permanent; rewrite ^/gongyi$ http://m.b.mohui.com/commonweal permanent; rewrite ^/news$ http://m.b.mohui.com/info permanent; }
2. PC 端配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 # PC端配置和移动端大同小异,不再赘述 server { listen 80; server_name mc.b.mohui.com; autoindex on; index index.html home_page.html; rewrite ^/(\.html)?$ http://mc.b.mohui.com/home.html permanent; rewrite ^/commonweal\.html$ http://mc.b.mohui.com/gongyi.html permanent; rewrite ^/info\.html$ http://mc.b.mohui.com/news.html permanent; if ( $http_user_agent ~* '(Android | webOS | iPhone | iPod | BlackBerry)') { rewrite ^(.*)\.html http://m.b.mohui.com$1 permanent; }
rewrite 指令的最后一项参数为 flag 标记,其可选值如下。
last:相当于 apache 里面的[L]标记,表示 rewrite。 break:本条规则匹配完成后,终止匹配,不再匹配后面的规则。 redirect:返回 302 临时重定向,浏览器地址会显示跳转后的 URL 地址。 permanent:返回 301 永久重定向,浏览器地址会显示跳转后的 URL 地址。 二、同域名的跳转 假设在 /usr/share/nginx/
目录下新建两个文件夹,分别为 pc 和 mobile 目录。
1 2 3 cd /usr/share/nginx mkdir pc mkdir mobile
在两个目录下分别新建一个 index.html 文件。则在 conf.d
目录下找到对应 conf 文件配置如下:
1 2 3 4 5 6 7 8 9 10 11 server{ listen 80; server_name nginx2.jspang.com; location / { root /usr/share/nginx/pc; if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') { root /usr/share/nginx/mobile; } index index.html; } }