How to Use Nginx to Serve Separate PC and Mobile Sites with Auto Detection
This guide explains how to configure Nginx to automatically detect user devices and redirect them to distinct PC or mobile websites, using both server‑side User‑Agent checks and client‑side JavaScript with cookies for manual switching and 24‑hour preference storage.
In recent years, with the widespread use of smartphones and tablets, more users access websites via mobile clients, making responsive web design popular. Although responsive design is a front‑end technique, this article focuses on using Nginx to serve separate PC and mobile sites.
The goal is to have two physically isolated sites (www.264.cn for PC and m.264.cn for mobile) so that each can deliver optimized content, reduce bandwidth, and allow users to switch manually when detection is wrong.
Requirements:
Two sites: PC (www.264.cn) and mobile (m.264.cn).
Any device accessing either domain should be redirected to the appropriate site.
Users can manually switch between versions, with a link on each side.
The chosen version is remembered for 24 hours (configurable).
Simple server‑side solution
Place PC files in /usr/local/website/web and mobile files in /usr/local/website/mobile, then modify Nginx configuration to check the User‑Agent string. Example configuration:
location / {
# Default PC site
root /usr/local/website/web;
# Mobile detection via User‑Agent
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‑side JavaScript solution
Insert the following script into the <head> of the homepage to redirect based on User‑Agent and optional query parameter:
<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)){
window.location.href="http://m.264.cn"; // mobile site
}else if(/iPad/i.test(navigator.userAgent)){
// iPad – no redirect
}else{
window.location.href="http://wap.264.cn"; // fallback mobile
}
}catch(e){}
}
}
// ]]></script>Recommended combined approach
Use JavaScript to set a cookie indicating the preferred version, and let Nginx rewrite requests based on both the User‑Agent and the cookie.
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++) {
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);
} 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;
}On the mobile page, add a link to switch to the PC version and set a cookie to remember the choice for 24 hours:
<a onclick="createCookie('iphone_mode', 'full', 1, '264.cn')" href="http://www.264.cn">Desktop version</a>On the PC page, add a link to switch to the mobile version and delete the cookie:
<a onclick="eraseCookie('mobile_mode', '264.cn');" href="http://m.264.cn">Mobile version</a>Full Nginx configuration examples
PC site configuration (unrelated directives omitted):
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;
}
if (!-f $request_filename) {
proxy_pass http://app_server;
break;
}
}
}Mobile site 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;
}
if (!-f $request_filename) {
proxy_pass http://m_app_server;
break;
}
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
