Nginx to distinguish between PC or mobile phone access to different websites

Source: Internet
Author: User
Tags setcookie lenovo

In recent years, with the popularity of mobile phones and pad, more and more users choose to use mobile clients to access the site, and in order to obtain a better user experience, it is necessary to display the most suitable match for different devices, this is the popular "responsive web Design" in recent years.

Responsive web Design is a pure front-end technology JS, CSS and other implementations for different devices to access the same URL to see different layouts, is the page content is more suitable for the current device reading. But this is not the focus of this article, the focus is on how to implement the Nginx.

This article is about how to use Nginx to distinguish between PC and mobile phone access to different websites, is physically completely isolated two sets of sites (a set of mobile, a set of PC-side), so that the benefits of PC and mobile content can not be the same, mobile version of the site does not need to contain a special many content, This saves traffic by simply including the necessary text and a smaller picture. The advantage of course will increase the difficulty, the problem is that you need to maintain two sets of environment, and need to automatically identify the user's physical device and jump to the appropriate website, when the user can manually switch back to the correct site when judging the error.

The following is a Chinese business network as an example to illustrate how to achieve the above requirements.
Clear requirements:
1. Make two site PC-side website www.264.cn, and mobile website m.264.cn
2. Accessing any domain name using a PC or mobile device will jump to the appropriate site.
3. The user can choose to access the mobile version or the PC version of the website, the mobile version of the website always has a switch to the PC version of the link, the PC version when the website through the mobile phone will provide a mobile version of the site link.
4. When the user has chosen to access one of these types of sites, the Save settings result is valid for 24 hours, of course, the length can be set by itself.

A simple server-side implementation approach
There are two sets of website code, a set of PC version placed in/usr/local/website/web, a set of mobile version placed in/usr/local/website/mobile. Only need to modify Nginx configuration file, Nginx through the UA to determine whether from the mobile access, to achieve different client access to different content.
The disadvantage of this method is the mobile and PC side with the same domain name, there is a suspicion of black hat, and UA is not always judged accurate, if the wrong case, users can not manually modify the type of Web site access.
The key Nginx configurations are as follows:

 location / {#默认PC端访问内容     root /usr/local/website/web; #如果是手机移动端访问内容     if  (  $http _user_agent ~  "(MIDP) | ( WAP) | (UP. Browser) | (Smartphone) | (Obigo) | (Mobile) | (AU. Browser) | (WxD. MMS) | (Wxdb.browser) | (CLDC) | (UP. Link) | (KM. Browser) | (UCWEB) | (Semc\-browser) | (Mini) | (Symbian) | (Palm) | (Nokia) | (Panasonic) | (mot\-) | (SonyEricsson) | (nec\-) | (Alcatel) | (Ericsson) | (BENQ) | (BenQ) | (amoisonic) | (amoi\-) | (Capitel) | (PHILIPS) | (SAMSUNG) | (Lenovo) | (Mitsu) | (Motorola) | (Sharp) | (Wapper) | (lg\-) | (lg/) | (EG900) | (CECT) | (Compal) | (Kejian) | (Bird) | (BIRD) | (g900/v1.0) | (Arima) | (CTL) | (TDG) | (Daxian) | (Daxian) | (Dbtel) | (eastcom) | (eastcom) | (Pantech) | (Dopod) | (Haier) | (HAIER) | (Konka) | (Kejian) | (LENOVO) | (Soutec) | (Soutec) | (SAGEM) | (sec\-) | (sed\-) | (emol\-) | (INNO55) | (ZTE) | (IPhone) | (Android) | (WINDOWS CE) | (Wget) | (Java) | (Curl) | (Opera) " " {root /usr/local/website/mobile;} index index.html index.htm;} 

Pure Client JS implementation
The following code is placed between the home

<script type= "Text/javascript" >// <! [Cdata[if (/applewebkit.*mobile/i.test (navigator.useragent)  | |   (/midp| symbianos| nokia| Samsung| Lg| nec| tcl| alcatel| bird| dbtel| dopod| philips| haier| lenovo| mot-| nokia| sonyericsson| sie-| amoi| Zte/.test (navigator.useragent)) {if (Window.location.href.indexOf ("mobile") <0) {try{if (/android|webos|iphone |ipod| Blackberry/i.test (navigator.useragent)) {                                  //Touch screen Mobile address window.location.href= "http://m.264.cn";} Else if (/ipad/i.test (navigator.useragent)) {                                  //pad Version Address}else{                                 // Normal mobile address window.location.href= "http://wap.264.cn"}}catch (e) {}}}// ]]></script>

Recommended Nginx differential phone and PC access methods
Using the front-end JS and back-end nginx with, JS set a cookie to set the current access to which page.

Add the JS code that sets the cookie, which needs to be placed on all pages of the mobile website and PC site.

Function createcookie (Name, value, days, domain, path)  {  var  expires =  ';  if  (days)  {    var d = new  date ();     d.settime (D.gettime ()  +  (days*24*60*60*1000));     expires =  ';  expires= '  + d.togmtstring ();   }  domain  = domain ?  ';  domain= '  + domain :  ';   path =   ';  path= '  +  (path ? path :  '/');   document.cookie =  name +  ' = '  + value + expires + path + domain;} Function readcookie (name)  {  var n = name +  ' = ';   var  cookies = document.cookie.split (';');   for  (var i = 0; i < cookies.length; i++) &NBsp {    var c = cookies[i].replace (/^\s+/,  ');     if   (C.indexof (n)  == 0)  {      return c.substring (n.length );     }  }  return null;} Function erasecookie (Name, domain, path)  {  setcookie (name,  ",  -1,  domain, path);}

Nginx adds the following configuration to determine whether the current mobile or PC-side access is based on UA and Cookie

if ($http _user_agent ~* ' (android|webos|iphone|ipod| BlackBerry) {  set $mobile _request ' 1 ';} if ($http _cookie ~ ' Mobile_request=full ') {  set $mobile _request ';} if ($mobile _request = ' 1 ') {  rewrite ^.+ Http://m.264.cn$uri;}

Add a link to the PC version of the mobile page
The default user will come in to judge the UA, if it is mobile phone access will enter the mobile version, but there will be a miscalculation into the mobile version or need more information into the PC version, then you need to put in the mobile version of the page code, so that users can switch from the mobile version to the Web version and the next visit will retain the settings.

<a onclick= "Setcookie (' Iphone_mode ', ' full ', 1, ' 264.cn ')" href= "http://www.264.cn" > Computer edition </a>

If user access is not correct, click on the computer version of the link can go to the PC version of the website, and again within 24 hours to remember the last access to the site type settings.

PC version of the website to increase access to the mobile version of the link
Add the following link in the appropriate place on the PC version of the website so that users can switch to the mobile version of the website.

<a onclick= "Deletecookie (' Mobile_mode ', ' 264.cn ');" href= "http://m.264.cn" > Mobile version </a>

The complete Nginx configuration, of course, is removed from the functionality of this article is not related to the configuration, not a complete set of available configurations, just give everyone a whole framework.

PC version of Web site configuration

upstream app_server {  server 0.0.0.0:9001;} Server {  listen 80;  server_name www.264.cn;  root /path/to /main_site;  # ...  location / {    proxy_set_header  X-Real-IP  $remote _addr;    # ...    if  ($http _ user_agent ~*  ' (android|webos|iphone|ipod| BlackBerry)  {      set  $mobile _request  ' 1 ';     }    if  ($http _cookie ~  ' mobile_request=full ')  {       set  $mobile _request  ';     }    if   ($mobile _request =  ' 1 ')  {      rewrite ^.+ http:/ /M.264.CN$URI;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;#&NBSP;SERVE&NBSP;CACHED&NBSP;PAGES&NBSP, .....     if  (!-f  $request _filename)  {      proxy_pass http:// app_server;      break;    }  }}

Mobile phone configuration

upstream m_app_server {server 0.0.0.0:9001;} server {  listen 80;  server_name m.264.cn;  root /path/to/ Mobile_site;  # ...  location / {    proxy_set_header  X-Real-IP  $remote _addr;    # ...    if  ($http _ user_agent ~*  ' (android|webos|iphone|ipod| BlackBerry)  {      set  $mobile _request  ' 1 ';     }    if  ($http _cookie ~  ' mobile_request=full ')  {       set  $mobile _request  ';     }    if   ($mobile _request !=  ' 1 ')  {      rewrite ^.+ http ://www.264.cn$uri;    }    # serve cached pages  ...     if  (!-f  $request _filename)  {      proxy_pass http://m_app_ server;      break;    }  }}

Nginx to distinguish between PC or mobile phone access to different websites

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.