将Vite+React项目部署到Apache子目录出现404错误求助
解决Vite+React项目部署到Apache子目录的404问题
问题分析
访问https://example.com/subfolder时favicon和页面标题能正常显示,说明index.html已被加载,但单页应用的路由无法正确处理——核心原因是.htaccess的重写规则错误指向了根目录的index.html,而非子目录下的入口文件。
修复步骤
1. 修正.htaccess配置
将/var/www/html/subfolder/下的.htaccess修改为以下内容,适配子目录的路由重写逻辑:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /subfolder/ RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /subfolder/index.html [L] </IfModule>
RewriteBase /subfolder/:指定重写的基准路径为目标子目录- 最后的
RewriteRule明确指向子目录下的index.html,确保所有非文件/目录的请求都转发到单页应用入口
2. 配置Apache允许.htaccess生效
确保Apache开启了重写模块,并允许子目录使用.htaccess:
- 开启
mod_rewrite模块:sudo a2enmod rewrite sudo systemctl restart apache2 - 修改站点配置文件(例如
/etc/apache2/sites-available/000-default.conf),在子目录的<Directory>块中添加AllowOverride All:
保存后重启Apache:<Directory /var/www/html/subfolder> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory>sudo systemctl restart apache2
3. 确认Vite配置完整性
检查vite.config.js是否存在语法错误,修正后的完整配置如下:
export default defineConfig({ build: { rollupOptions: { input: 'index.html' } }, base: '/subfolder/', plugins: [react()], })
重新执行npm run build,将生成的dist目录文件覆盖到/var/www/html/subfolder。
验证
重新访问https://example.com/subfolder,单页应用的路由应正常工作,不再出现404错误。
内容的提问来源于stack exchange,提问作者dexcaped
相关产品推荐
相关产品推荐

