问题描述

vue3项目部署后,网站可以从首页进入可以访问其他路由页面,但刷新页面或直接进入某个路由地址时报错404

原因分析:

在 Vue 3 项目部署后,遇到首页可以访问但刷新或直接访问某个路由地址时报 404 错误的问题,通常是由于服务器没有正确配置路由策略。这是一个常见的问题,因为现代前端框架(如 Vue.js)使用客户端路由,而大多数服务器默认使用服务器路由。

当你在浏览器中直接访问一个 URL(例如 http://example.com/some-route),浏览器会向服务器请求这个具体的路径。如果服务器没有配置来处理这个请求,它会返回一个 404 错误。然而,在客户端路由的情况下,你希望所有请求都返回你的 index.html,然后由 Vue Router 处理客户端的路由逻辑。


解决方案:

解决这个问题的方法是配置服务器,使其将所有的路由请求都指向 index.html。具体的配置方法取决于你使用的服务器环境。

  1. Nginx
    如果你使用的是 Nginx,配置文件(通常是 nginx.conf 或一个站点配置文件)应该包含以下内容:
server {
    listen 80;
    server_name example.com;

    root /path/to/your/vue-app/dist;
    index index.html;

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

    # Serve static files directly
    location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
        try_files $uri =404;
    }
}

  1. Apache
    如果你使用的是 Apache,配置文件(通常是 .htaccess)应该包含以下内容:
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

  1. Node.js (Express)
    如果你使用的是 Node.js 和 Express.js,配置文件应该如下:
const express = require('express');
const path = require('path');

const app = express();

const staticPath = path.join(__dirname, 'dist');
app.use(express.static(staticPath));

app.get('*', (req, res) => {
  res.sendFile(path.join(staticPath, 'index.html'));
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

总结

通过正确配置服务器,将所有路由请求都指向 index.html,可以确保 Vue Router 能够处理客户端的路由逻辑,从而避免在刷新页面或直接访问某个路由地址时出现 404 错误。选择具体的配置方法取决于你的服务器环境。

GitHub 加速计划 / vu / vue
97
16
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:8 个月前 )
9e887079 [skip ci] 6 个月前
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 10 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐