Nginx 的 index 指令不支持按 User-Agent 动态切换首页,需用 map + try_files 或 if + rewrite 实现;推荐在 http 块中用 map 映射 UA 到不同首页文件,再通过 try_files 加载,确保文件存在于 root 目录下。
在 Nginx 中,
指令本身不支持按
动态切换首页文件,它只声明一个静态的默认索引文件列表(如
),由 Nginx 在请求目录时自动查找。要实现“不同 User-Agent 返回不同首页”,需绕过
的限制,改用
+
或条件重写方式。
用 map 定义 User-Agent 对应的首页文件
这是最清晰、高效的做法:先根据请求头映射出目标首页路径,再通过
或
加载对应文件。
在
块中定义映射:
然后在
或
中使用:
注意:
第一项是带前导
的 URI 路径,Nginx 会按 location 规则匹配该路径(相当于内部重定向),最终返回对应文件内容。确保这些文件真实存在于 root 目录下。
用 if + rewrite 实现简单判断(不推荐用于复杂场景)
若仅需少量 UA 判断,也可用
,但需注意:
在 location 中有局限性,且嵌套逻辑易出错。
只能在
或
块中使用,不能嵌套
建议只做单次判断,并用
终止后续处理
例如:
注意事项与常见问题
map 必须定义在 http 块顶层
,不能放在 server 或 location 内
正则匹配区分大小写
:用
表示忽略大小写,
表示大小写敏感
移动 UA 判断不可靠
:部分桌面浏览器可能伪造 Mobile 字样,建议结合 JS 或后端进一步识别
避免循环重定向
:若 rewrite 目标仍匹配当前 location,需加
或明确限定匹配范围(如用
)
静态文件需开启 sendfile
:确保 Nginx 能直接高效返回 HTML 文件,无需经由后端
验证是否生效
用 curl 模拟不同 UA 测试:
观察响应 body 是否为预期的
或
,并检查响应头中的
和状态码是否正常。
indexUser-Agentindex.html index.phpindextry_filesmaptry_filesrewritehttp
map $http_user_agent $mobile_index {
default "index.html";
"~*iPhone|Android|Mobile" "index-mobile.html";
"~*WeChat|MiniProgram" "index-wx.html";
}
serverlocation
location / {
try_files /$mobile_index =404;
}
try_files/ifififserverlocationrewrite ... break
location = / {
if ($http_user_agent ~* "(iPhone|Android)") {
rewrite ^(.*)$ /index-mobile.html break;
}
if ($http_user_agent ~* "WeChat") {
rewrite ^(.*)$ /index-wx.html break;
}
try_files /index.html =404;
}
~*~breaklocation = /index-mobile.html
curl -H "User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X)" http://your-site/
curl -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)" http://your-site/
index-mobile.htmlindex.htmlContent-Type