NginxPC端和移動端區分


現在隨着手機和pad的移動端普及,越來越多的用戶選擇使用移動客戶端訪問網站,而為了獲取更好的用戶體驗,就需要針對不同的設備顯示出最合適的匹配,這樣就是近年來流行的“響應式web設計”。

本文要講的的是如何使用nginx區分pc和手機訪問相同的網站,是代碼上完全隔離的兩套網站(一套移動端、一套pc端),這樣帶來的好處pc端和移動端 的內容可以不一樣,移動版網站不需要包含特別多的內容,只要包含必要的文字和較小的圖片,這樣會更節省流量。有好處當然也就會增加困難,難題就是你需要維護兩套環境,並且需要自動識別出來用戶的物理設備並跳轉到相應的網站,當判斷錯誤時用戶可以自己手動切換回正確的網站。

 

NGINX區分PC端和手機端配置

server
    {
        listen 80;
        server_name  mike.com;
        index index.php index.html index.htm default.html default.htm default.php;
        root  /www/site/mike.com;


       add_header Set-Cookie "site_type=1;Path=/";
           set $is_mobile no;
       if ($http_user_agent ~* "(mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)") {

           set $is_mobile yes;

       }

       location / {
            add_header Access-Control-Allow-Origin *;
            if ($is_mobile = "yes") {
            root /www/site/mike.com/m;
            }
            ssi on;
        }
          
       location /m {
            ssi on;

       }

        location /uploads {

          proxy_pass http://www.baidu.com/uploads/;

        }


          location  /site_app/  {

       alias  /www/site/app/;
        
        }


        location = /favicon.ico {
            log_not_found off;
            access_log off;
        }


      location ~ /\.  {
           deny all;
           access_log off;
           log_not_found off;
       }

}

其中主要區分PC端和手機端的配置是以下這里

           set $is_mobile no;
       if ($http_user_agent ~* "(mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)") {

           set $is_mobile yes;

       }

       location / {
            add_header Access-Control-Allow-Origin *;
            if ($is_mobile = "yes") {
            root /www/site/mike.com/m;
            }
            ssi on;
        }
          
       location /m {
            ssi on;

       }

根據網站根路徑下目錄進行區分的,PC 端路徑代碼是  /www/site/mike.com,移動端端路徑代碼是  /www/site/mike.com/m

這樣就可以電腦打開自動判斷到PC端路徑下的代碼,手機打開直接判斷到 移動端路徑下的代碼

實現功能

PC端輸入打開  mike.com  URL自動跳到PC端代碼下

移動端輸入打開 mike.com  URL自動跳到移動端代碼下

這樣做的好處都是同一個域名,不用申請或者使用過多的二級域名~~~

 

本文分享完畢,感謝支持點贊~~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM