1. 程式人生 > 實用技巧 >Nginx PC端和移動端區分

Nginx PC端和移動端區分

現在隨著手機和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自動跳到移動端程式碼下

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

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