apache mod_rewrite生效需三步:启用模块(a2enmod或取消loadmodule注释)、在directory块中设置options +followsymlinks和allowoverride all/none、rewriteengine on后编写规则(路径匹配用^article/而非^/article/,推荐加[l]等标志)。

Apache 的 Rewrite 模块(mod_rewrite)必须显式加载并启用,才能支持 URL 重写和跳转。配置分三步:加载模块、允许重写权限、开启引擎并写规则——缺一不可。
确认并启用 mod_rewrite 模块
多数现代发行版默认已编译该模块,但未必启用。先检查是否已加载:
- Debian/Ubuntu 系统:
sudo a2enmod rewrite,然后sudo systemctl restart apache2 - RHEL/CentOS 系统:编辑
/etc/httpd/conf.modules.d/00-base.conf或/etc/httpd/conf/httpd.conf,确保有未注释行:LoadModule rewrite_module modules/mod_rewrite.so - 手动验证是否生效:
apache2ctl -M | grep rewrite(Ubuntu)或httpd -M | grep rewrite(RHEL),输出含rewrite_module (shared)即表示已加载
在虚拟主机中授权重写行为
仅加载模块还不够。Rewrite 规则要生效,必须在对应站点的 <directory></directory> 块中明确放行,并配齐必要选项:
- 不能只在
<virtualhost></virtualhost>根层级写RewriteEngine On,必须包裹在<directory></directory>内 - 必需设置:
Options +FollowSymLinks(否则常见 500 错误)、AllowOverride None或All(若用 .htaccess 则设为 All;若直接写在配置里,可设为 None) - 示例片段:
<directory><br> Options +FollowSymLinks<br> AllowOverride None<br> Require all granted<br></directory>
启用引擎并编写有效规则
在已授权的 <directory></directory> 块内启用引擎,并注意规则写法细节:
- 必须写
RewriteEngine On—— 每个 VirtualHost 都要单独开启,不继承 - 路径匹配以
^article/开头,不是^/article/(服务器级配置中前导斜杠被剥离) - 每条规则末尾建议加标志,如
[L](终止后续匹配)、[R=301](永久跳转),避免意外连锁重写 - 简单测试规则(重定向 /old → /new):
RewriteRule ^old$ /new [R=301,L]
改完配置后务必重启服务:sudo systemctl restart apache2(Debian系)或 sudo systemctl restart httpd(RHEL系)。规则不生效,90% 是因为没在 Directory 块里开引擎,或 AllowOverride 设为 None 却指望 .htaccess 生效。











