Tim's Blog

Tim's Blog

解决因前端路由模式导致页面刷新404问题

2025-06-27

记录一下在访问 UniApp 发布的网站时,刷新页面后出现 404 问题并通过AI解决

📌问题现象:

使用 Uniapp 开发的 H5 项目部署后直接访问 https://example.com/pages/home/home 能正常加载,但是刷新页面时出现 404 错误。

OpenResty/Nginx 错误日志显示:

  open() "/www/wwwroot/your-site/pages/home/home" failed (2: No such file or directory)

🧩问题原因:

1. 前端路由模式问题

  • UniApp 使用 History 模式。

  • URL 显示为真实路径(如 /pages/home/home ),但实际不存在对应的物理文件。

2. 服务器配置问题

Nginx/OpenResty 尝试查找真实文件路径-,找不到对应文件时返回 404

🛠️解决方案:

修改 Nginx/OpenResty 网站配置,添加下面代码:

 location / {
        try_files $uri $uri/ /index.html; 
    }

⚠️注意事项:

配置生效

修改配置后必须重启 Nginx/OpenResty

# 检查配置语法
nginx -t

# 重新加载配置
nginx -s reload

📚原理说明:

try_files 指令

try_files $uri $uri/ /index.html;

执行顺序为:

  1. 尝试访问 $uri(原始请求路径)

  2. 尝试访问 $uri/(作为目录)

  3. 如果都不存在,返回 /index.html (依照具体路径)

最后前端路由接管URL解析。