You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将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:
    <Directory /var/www/html/subfolder>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    保存后重启Apache:
    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 16:19:58