mod_rewrite 默认未启用,需手动开启模块、配置 allowoverride all 并设置 rewriteengine on 才能生效;ubuntu 用 a2enmod rewrite,rhel 系统需编辑 httpd.conf 加载模块。
apache 的 mod_rewrite 模块默认通常不启用,需手动开启并配置才能使用 url 重写功能。启用后还需确保站点支持 `.htaccess` 或主配置中正确加载规则,否则规则不会生效。
确认并启用 mod_rewrite 模块
在 Linux 系统(如 Ubuntu/Debian 或 CentOS/RHEL)中操作:
-
Ubuntu/Debian:运行
sudo a2enmod rewrite,然后重启 Apache:sudo systemctl restart apache2 -
CentOS/RHEL(含 Rocky/AlmaLinux):编辑
/etc/httpd/conf/httpd.conf,取消注释或添加一行:LoadModule rewrite_module modules/mod_rewrite.so,再执行sudo systemctl restart httpd - 验证是否启用成功:运行
apache2ctl -M | grep rewrite(Debian系)或httpd -M | grep rewrite(RHEL系),输出含rewrite_module (shared)即表示已加载
允许 .htaccess 中使用 RewriteRule
仅启用模块还不够,Apache 默认禁止目录级重写。需在虚拟主机配置或主配置中设置权限:
- 找到对应站点的
<directory></directory>块(例如/var/www/html),确保包含以下配置:
<directory>
AllowOverride All
Require all granted
</directory>
⚠️ 注意:AllowOverride None 会完全忽略 .htaccess 文件;设为 All 才允许 RewriteEngine、RewriteRule 等指令生效。
Apache Superset 是一个广泛采用的开源 BI 平台,用于 SQL 探索、图表构建和仪表板交付。当代理需要查询仓库数据、组装仪表板或使用成熟的分析界面解释指标而不是临时笔记本代码时,此技能非常有用。
写一个基础规则测试是否工作
在网站根目录创建 .htaccess 文件,内容如下:
RewriteEngine On RewriteRule ^test$ index.html [L]
说明:
-
RewriteEngine On是必需的开关,没有它所有规则都不执行 -
^test$匹配精确访问路径/test(不带斜杠) -
index.html是目标文件,Apache 内部重写(URL 不变,但返回 index.html 内容) -
[L]表示“最后一条规则”,匹配后不再执行后续规则
保存后访问 http://your-domain/test,若看到首页内容(而非 404),说明 mod_rewrite 已正常工作。
常见失败原因快速排查
- Apache 配置未重载:改完
httpd.conf或apache2.conf后忘记systemctl restart - .htaccess 放错位置:必须放在被请求的 URL 对应的物理目录下,且该目录在
<directory></directory>中设置了AllowOverride All - 规则语法错误:比如漏写
RewriteEngine On,或正则表达式写成test/却访问/test - SELinux(RHEL系)限制:若启用了 SELinux,可能阻止读取 .htaccess,可临时用
setsebool -P httpd_read_user_content 1授权










