如何在Apache2服务器部署Vue3(Vite)应用及问题排查
解决Vite Vue3应用在Apache2上部署的页面空白问题
问题核心
你的配置存在两个关键问题:一是Vite打包的base路径与实际访问路径不匹配,二是Apache未配置单页应用的路由 fallback,且当前VirtualHost配置与你实际的访问方式(服务器IP+/agenda/dist)不兼容。
解决方案步骤
1. 修正Vite的base配置
因为你是通过服务器IP/agenda/dist路径访问应用,需要在Vite配置中指定正确的base路径,避免手动修改资源路径。
修改项目根目录的vite.config.js:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], base: '/agenda/dist/' })
执行重新打包命令:
yarn run build
2. 调整Apache配置(二选一)
选项A:通过服务器IP/agenda/dist访问(临时测试用)
不需要单独的VirtualHost,直接修改默认站点配置(/etc/apache2/sites-available/000-default.conf),添加以下目录规则:
<Directory /var/www/html/agenda/dist> Options -Indexes +FollowSymLinks AllowOverride All Require all granted # 单页应用路由 fallback 配置 RewriteEngine On RewriteBase /agenda/dist/ RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /agenda/dist/index.html [L] </Directory>
选项B:使用VirtualHost直接访问(推荐,适配后续DNS配置)
修改你的VirtualHost配置文件,添加ServerName(用服务器IP临时替代)和单页应用fallback规则:
<VirtualHost *:80> ServerName 你的服务器IP地址 ServerAdmin webmaster@localhost DocumentRoot /var/www/html/agenda/dist ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/html/agenda/dist> Options -Indexes +FollowSymLinks AllowOverride All Require all granted # 单页应用路由 fallback 配置 RewriteEngine On RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </Directory> </VirtualHost>
之后重启Apache服务:
sudo systemctl restart apache2
直接访问服务器IP即可打开应用,无需添加/agenda/dist后缀。
3. 修复图标路径
当前index.html中的图标路径为/hrg.ico,需根据选择的访问方式调整:
- 若选选项A:改为
./hrg.ico或/agenda/dist/hrg.ico - 若选选项B:确保
hrg.ico文件在/var/www/html/agenda/dist目录下,路径保持/hrg.ico即可
内容的提问来源于stack exchange,提问作者Gabriel Pereira
相关产品推荐
相关产品推荐

