1panel部署静态网站的时候怎么避免单页应用404

134 次阅读

本文最后更新于 2026年5月3日。

在 1Panel 上部署 Vue/React 等 SPA 时,出现“刷新 404”是因为 Nginx 默认按真实路径找文件,而 history 模式路由实际上只有一个 index.html。解决核心:在网站 Nginx 配置里加 try_files 规则,把所有不存在的路径都回退到 /index.html

直接更改nginx配置

一、操作步骤(1Panel)

  1. 登录 1Panel → 网站 → 找到你的站点 → 点击「配置」(Nginx 配置)。

  1. server { … } 内部,找到或添加 location / { … },确保包含以下关键行:
location / {
    root    /www/wwwroot/你的站点目录;  # 确认是你的dist目录
    index   index.html;
    try_files $uri $uri/ /index.html;  # 核心:不存在就回退到index.html

    # 可选:禁止html缓存,避免更新后不生效
    if ($request_filename ~* \.(htm|html)$) {
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }
}
  1. 保存配置 → 重启 Nginx(或在面板点「重载配置」)。

二、配置说明(为什么这样写)

  • $uri:先尝试请求的文件(如 /js/main.js)。
  • $uri/:再尝试作为目录。
  • /index.html:都找不到,就返回首页,由前端路由接管。
  • 适用于:Vue(createWebHistory)、React(BrowserRouter)等 history 模式 SPA。

三、常见坑与排查

  • ❌ 根目录错:root 必须指向 dist 文件夹(里面直接有 index.html),不要套一层。
  • ❌ 配置没生效:改完必须 重载 Nginx;可在服务器执行 nginx -t 检查语法。
  • ❌ 前端路由 base:如果部署在子目录(如 域名/app/),前端需设置 base: '/app/',并同步调整 Nginx 的 location 与 root。

四、完整示例(可直接复制)

server {
    listen 80;
    server_name yourdomain.com;
    root /www/wwwroot/yourdomain.com;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
        if ($request_filename ~* \.(htm|html)$) {
            add_header Cache-Control "no-cache, no-store, must-revalidate";
        }
    }

    # 静态资源缓存(可选,提升性能)
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
    }
}

也可以直接在伪静态里可视化设置

1Panel 支持可视化设置,直接在「伪静态」里填规则就行

一、可视化操作(伪静态设置)

  1. 登录 1Panel → 网站 → 你的站点 → 配置

  2. 切换到 伪静态 选项卡(就是可视化设置区)。

  3. 选择「自定义」,在输入框直接填:

location / {
    try_files $uri $uri/ /index.html;
}
  1. 保存 → 重载 Nginx(面板右上角「重载配置」)。
    ✅ 这样就能解决 SPA 刷新 404,完全可视化、不用写完整配置。

二、为什么伪静态可行

  • 1Panel 的「伪静态」就是专门放 location 重写/路由规则 的可视化入口。
  • 对 Vue/React(history 模式),核心就是 try_files 把所有不存在的路径指向 /index.html
  • 伪静态里只写上面那 4 行即可,不用加 server、root、listen 这些,面板会自动合并到主配置。

三、补充(可选优化)

在伪静态里可以一起加上缓存控制(避免更新后不生效):

location / {
    try_files $uri $uri/ /index.html;
    if ($request_filename ~* \.(htm|html)$) {
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }
}

# 静态资源缓存(可选)
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    expires 30d;
    add_header Cache-Control "public, max-age=2592000";
}