You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx如何根据User Agent分发两套仓库构建产物并解决500错误

问题根因

你遇到的500错误是Nginx内部重定向次数超过默认上限(10次)触发的,本质是动态$root变量配合try_files末尾的/index.html fallback写法存在缺陷:每次内部重定向到/index.html都会重新触发路由匹配,反复走try_files逻辑形成死循环。桌面端访问正常只是巧合,配置本身的问题是通用的。

解决方案

按如下步骤修改配置即可解决:

1. 完善映射规则

先补全$root_content的tablet分支处理,同时去掉配置中多余的引号减少匹配歧义:

map $sent_http_content_type $expires {
    default off;
    text/html epoch;
    text/css max;
    application/javascript max;
    ~image/ max;
    ~font/ max;
}

map $http_user_agent $ua_device {
    default desktop;
    ~*(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|mobile.+firefox|netfront|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ ce|xda|xiino/i mobile;
    ~*android|ipad|playbook|silk/i tablet;
}

map $ua_device $root_content {
    default /www/web;
    mobile /www/mobile;
    # 若需要平板访问移动端资源则保留下面这行,不需要则删除,平板将默认走桌面端资源
    tablet /www/mobile;
}

2. 重写server块避免重定向循环

将try_files的fallback逻辑替换为命名location配合rewrite ... break,直接终止重定向流程,读取对应目录下的index.html:

server {
    listen 80 default_server;
    server_name _;
    root $root_content;
    index index.html index.htm;
    expires $expires;

    location / {
        try_files $uri $uri/ @fallback;
    }

    location @fallback {
        rewrite ^ /index.html break;
    }
}

3. 额外检查项

修改配置重载Nginx前确认两点:

  • /www/mobile目录下确实存在构建生成的index.html文件
  • Nginx运行用户(通常为nginx或www-data)对/www/mobile目录及下属所有文件有可读权限

内容的提问来源于stack exchange,提问作者Saurabh Pabhare

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 04:06:08