Vue.js项目部署后刷新页面出现404错误问题求助
这个问题我碰到过好多次了,本质是Vue的history模式路由和服务器物理路径逻辑不匹配导致的:
当你点击页面内的菜单时,是Vue的前端路由在浏览器内部跳转,不会向服务器发起新的请求;但刷新页面时,浏览器会直接向服务器请求www.sample.com/vue-project/add这个路径,而服务器上根本没有add这个物理文件或目录,所以返回404。
下面是完整的解决步骤:
1. 先确保Vue项目本身的配置正确
(1)设置打包的公共路径
在项目根目录的vue.config.js(如果没有就新建一个)里添加:
// Vue 3 用 publicPath,Vue 2 用 baseUrl module.exports = { publicPath: '/vue-project/' }
这个配置会让打包后的所有资源都以/vue-project/作为基础路径,避免资源加载失败。
(2)配置路由的base路径
在你的路由配置文件(比如src/router/index.js)里,给VueRouter添加base属性,并且保持mode: 'history':
import Vue from 'vue' import VueRouter from 'vue-router' import routes from './routes' Vue.use(VueRouter) const router = new VueRouter({ mode: 'history', // 必须是history模式才会出现这个问题,hash模式不会触发404 base: '/vue-project/', // 和publicPath保持一致 routes }) export default router
2. 配置服务器重写规则(核心步骤)
这一步是让服务器把所有/vue-project/下的非文件/非目录请求,都转发到/vue-project/index.html,让Vue的前端路由接管处理。
如果你用Nginx:
找到你的站点配置文件(通常在/etc/nginx/sites-available/或/etc/nginx/conf.d/下),在server块里添加如下配置:
location /vue-project/ { # 先尝试访问请求的文件/目录,找不到就返回index.html try_files $uri $uri/ /vue-project/index.html; }
配置完成后,重启Nginx生效:sudo systemctl restart nginx
如果你用Apache:
在服务器上/vue-project/对应的文件夹里,新建一个.htaccess文件,写入以下内容:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /vue-project/ # 直接访问index.html的话不做处理 RewriteRule ^index\.html$ - [L] # 如果请求的不是文件,也不是目录 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # 转发到index.html RewriteRule . /vue-project/index.html [L] </IfModule>
注意要确保Apache已经开启了mod_rewrite模块,比如Ubuntu下可以用sudo a2enmod rewrite,然后重启Apache:sudo systemctl restart apache2
如果你用IIS:
在项目根目录新建web.config文件,添加以下重写规则:
<configuration> <system.webServer> <rewrite> <rules> <rule name="Handle Vue History Mode" stopProcessing="true"> <match url=".*" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> <add input="{REQUEST_URI}" pattern="^/(vue-project)" negate="false" /> </conditions> <action type="Rewrite" url="/vue-project/index.html" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
完成以上配置后,重新刷新页面应该就能正常加载了。
内容的提问来源于stack exchange,提问作者Sam Teng Wong

