rewritebase 是关键定位器,用于定义 rewriterule 中相对路径的解析起点;必须与实际访问 url 路径严格一致且末尾带斜杠,如部署在 /app/ 则须写 rewritebase /app/,否则会导致路径错位、404 或白屏。

Apache 的 mod_rewrite 在子目录中工作时,RewriteBase 不是可选项,而是关键定位器——它告诉重写引擎“当前规则所处的 URL 上下文从哪开始”,避免路径计算错位。没设对,RewriteRule 中的相对路径替换(比如 index.html)就可能指向错误位置,导致 404 或白屏。
RewriteBase 的作用本质
RewriteBase 并不改变文件系统路径,也不影响请求匹配逻辑;它只定义 RewriteRule 替换目标中相对路径的解析起点。例如:
- 访问
https://example.com/blog/post-1 - 规则在
/var/www/html/blog/.htaccess中生效 - 若没设
RewriteBase /blog/,而写RewriteRule ^(.*)$ index.php,Apache 会尝试加载/var/www/html/index.php(根目录),而非预期的/var/www/html/blog/index.php - 加上
RewriteBase /blog/后,index.php就被正确解析为/blog/index.php对应的物理路径
怎么配才不踩坑
必须与实际访问 URL 路径严格一致,且末尾带斜杠:
Apache Superset 是一个广泛采用的开源 BI 平台,用于 SQL 探索、图表构建和仪表板交付。当代理需要查询仓库数据、组装仪表板或使用成熟的分析界面解释指标而不是临时笔记本代码时,此技能非常有用。
- 站点部署在根目录 →
RewriteBase / - 部署在
/app/→RewriteBase /app/(注意结尾/) - 部署在
/my-project/v2/→RewriteBase /my-project/v2/ - 绝对不要写成
RewriteBase /app(缺末尾斜杠)或RewriteBase app/(缺前导斜杠)
搭配 RewriteRule 的典型写法
以单页应用(SPA)二级目录为例,放在 /app/ 下:
RewriteEngine On
RewriteBase /app/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.html [L]
说明:
-
RewriteBase /app/确保index.html被解释为/app/index.html,而不是根目录下的index.html -
^(.*)$匹配所有路径(如/app/user/settings),但 Apache 在目录级上下文中已自动剥离了/app/前缀,所以规则里只写路径片段 -
[L]表示终止后续规则,防止冲突
常见失效原因排查
如果规则看似写了却没生效,重点检查这三项:
-
RewriteEngine On是否在同作用域(<directory></directory>块或 .htaccess)中启用 - 对应目录是否允许覆盖:
AllowOverride All(.htaccess 方式)或直接在配置块中写规则(推荐) -
RewriteBase值是否与浏览器地址栏中看到的 URL 前缀完全一致(区分大小写、斜杠、编码)










