Nginx可通过$ http_user_agent识别移动端并自动导向/m/页面,核心是结合map预定义$is_mobile变量、try_files优先匹配/m/index.html,或用rewrite静默重写路径。

当用户通过手机访问网站时,Nginx 可以在不依赖后端或 JavaScript 的前提下,自动将请求导向移动端专属页面(如 /m/index.html),关键在于合理配置 index 指令与 location 匹配逻辑,并结合 $http_user_agent 判断设备类型。
利用 index 指令配合 try_files 实现自动首页匹配
index 本身不支持条件跳转,但它可与 try_files 协同工作,为不同设备指定优先查找的首页文件。例如,先尝试加载移动版首页,失败则回退到 PC 版:
location / {
# 根据 UA 设置变量,标记是否为移动端
set $mobile "";
if ($http_user_agent ~* "(Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini)") {
set $mobile "_m";
}
<pre class='brush:php;toolbar:false;'># 尝试按顺序查找:/m/index.html → /index.html → 404
try_files /m$mobile/index.html /index.html =404;}
注意:set + if 在 location 中可用,但应避免在 server 级别大量使用;更健壮的做法是用 map 指令预定义变量。
用 map 预定义移动标识,提升性能与可读性
将 UA 判断提前到 server 上下文,用 map 创建一个轻量变量,避免每次请求都执行正则匹配:
map $http_user_agent $is_mobile {
default 0;
~*[Mm]obile 1;
~*[Aa]ndroid 1;
~*[iI]phone 1;
~*[iI]pad 1;
~*[Bb]lack[Bb]erry 1;
~*[Oo]pera [Mm]ini 1;
}
<p>server {
location / {
try_files /m$uri/index.html /m$uri$1 /$uri/index.html /$uri$1 /index.html =404;</p><h1>或更明确地:</h1><pre class='brush:php;toolbar:false;'> # try_files /m/index.html /index.html =404;
# 再配合 rewrite 或内部重定向实现路径隔离
}}
配合 rewrite 实现静默路径切换(推荐用于纯静态站点)
若移动端页面统一放在 /m/ 子目录下,可通过 rewrite 把手机用户请求“内部重写”过去,浏览器地址栏不变,但服务端返回的是移动版内容:
- 先判断是否为移动端,且当前请求路径不是
/m/开头 - 对根路径
/和常见静态入口(如/index.html)做重写 - 确保重写后仍能命中正确的 index 文件
if ($is_mobile = 1) {
rewrite ^/$ /m/ redirect;
rewrite ^/index\.html$ /m/index.html redirect;
}
# 注意:rewrite ... redirect 是 302 跳转;如需静默处理,去掉 redirect 并配合 root 或 alias
location /m/ {
alias /var/www/html/m/;
index index.html;
}
location / {
root /var/www/html;
index index.html;
}
注意事项与避坑提示
-
index指令只影响目录索引行为(即访问/dir/时找哪个文件),不能直接触发跳转;真正起作用的是try_files或rewrite - 避免在 if 中使用 break、return 等指令操作响应体,Nginx 官方不建议在 if 块中使用 rewrite 以外的指令
- 移动端检测仅靠 UA 不绝对可靠,适合内容差异大、需快速分流的场景;精细化适配建议交由前端 media query 或后端识别
- 启用 gzip、缓存策略和 HTTP/2,确保移动版资源加载效率不输 PC 版










