Nginx rewrite指令无法直接匹配User-Agent,需用if或map结合$http_user_agent实现移动端重写;推荐map预定义$is_mobile变量,在location中if判断后rewrite ^(.*?)$ /m$1 break,自动保留参数并加^/m/排除防循环。

Nginx 本身不支持在 rewrite 指令中直接捕获或匹配 User-Agent,因为 rewrite 只处理 URI 路径(location 匹配后的 $uri),不解析请求头。要基于 User-Agent 做重写(比如对移动端 UA 重写到 m/ 目录),必须用 if + $http_user_agent 判断,再配合 rewrite 或 return 实现。
用 if 判断 User-Agent 并 rewrite
这是最常用的方式。注意:if 在 location 外不推荐,应放在 server 或 location 块内;且 if 中的 rewrite 默认是内部重写(不跳转),加 redirect 或 permanent 才返回 302/301。
- 匹配移动端 UA(如微信、QQ 浏览器、iOS/Android 内置浏览器)并重写到
/m$uri - 使用
~*表示不区分大小写的正则匹配 - 避免在 if 中使用多个 rewrite,优先用一个 rewrite 覆盖逻辑
location / {
if ($http_user_agent ~* "(Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|UCBrowser)") {
rewrite ^(.*)$ /m$1 break;
}
}更安全的写法:用 map 预定义变量
相比 if,map 是 Nginx 推荐的条件映射方式,性能更好、无副作用(if 在某些上下文中可能引发非预期行为)。
- 在
http块中定义 map,将 UA 特征映射为一个开关变量(如$is_mobile) - 在 location 中用
if ($is_mobile)触发 rewrite,语义清晰且稳定
http {
map $http_user_agent $is_mobile {
default 0;
~*[Mm]obile 1;
~*Android 1;
~*iPhone 1;
~*iPad 1;
~*UCBrowser 1;
}
<pre class="brush:php;toolbar:false;">server {
location / {
if ($is_mobile) {
rewrite ^(.*)$ /m$1 break;
}
}
}}
重写后保留原始参数 & 避免循环
常见错误是 rewrite 后未处理 query string,或因路径重复匹配导致无限重写(例如 /m/ 又被再次匹配)。需注意:
-
rewrite ^(.*)$ /m$1 break;会自动携带原始参数(?a=1&b=2) - 加
^/m/的 location 排除规则,防止 /m/ 开头的请求再次进入 mobile 重写 - 用
break终止当前 location 的后续处理,避免多余匹配
调试技巧:临时记录 UA 和重写动作
加 access_log 或用 echo 模块(需编译)辅助验证。若没 echo 模块,可用 log_format 记录关键变量:
log_format debug '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_user_agent" "$is_mobile"';
<p>access_log /var/log/nginx/debug.log debug;</p>











