要让静态单页应用在 Apache 二级目录(如 /app/)下正确响应前端路由,需同时配置 DirectoryIndex index.html 和 mod_rewrite fallback 规则:启用 RewriteEngine,设置 RewriteBase /app/,并用 !-f 和 !-d 条件将非资源请求重写至 /app/index.html;还需确保 AllowOverride All 或直接在 Directory 块中配置,且构建时 publicPath 设为 '/app/'。
要让静态单页应用(如 Vue、React 构建的 SPA)在 Apache 的二级目录(例如 /app/)下正确响应路由,关键不是只靠 DirectoryIndex,而是配合 mod_rewrite 实现前端路由 fallback——即所有非资源请求(如 /app/user/profile)都回退到 /app/index.html,由前端路由接管。
在对应二级目录的配置中(如 <Directory "/var/www/html/app"> 或站点根目录下的 .htaccess),显式设置:
DirectoryIndex index.html
这确保访问 https://example.com/app/ 时能自动加载 index.html。但仅此一项无法解决子路径(如 /app/about)404 问题——因为 Apache 默认按真实文件路径匹配,而这些路径在服务端并不存在。
必须开启重写引擎,并在二级目录上下文中限制作用范围。推荐在 <Directory> 块或 .htaccess 中配置:
RewriteEngine OnRewriteBase /app/RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)$ /app/index.html [L]说明:
RewriteBase /app/:指定重写基准路径,避免路径计算错误(尤其在子目录中)!-f 和 !-d:仅对不存在的真实文件或目录才触发重写,保障 /app/static/js/app.js 这类资源正常返回^.*$ → /app/index.html:把所有匹配请求导向入口 HTML,由前端 router 渲染对应视图若通过 .htaccess 配置(放在 /var/www/html/app/.htaccess),需确保主配置中对应目录允许覆盖:
<Directory "/var/www/html/app">AllowOverride AllRequire all granted</Directory>
否则 .htaccess 不生效。生产环境更推荐直接在虚拟主机或目录块中配置,性能更好且更可控。
前端构建工具(如 Vue CLI、Create React App)需正确设置 publicPath:
vue.config.js 中设 publicPath: '/app/'
package.json 中设 "homepage": "http://example.com/app",并确保构建后资源引用路径为 /app/static/...
否则即使服务器配置正确,JS/CSS 加载也会 404。