温馨提示×

如何开启apache2重写模块

小樊
46
2026-09-21 17:25:56
栏目: 编程语言

在 Apache2 中开启 重写模块(mod_rewrite) 的方法如下,适用于 Ubuntu / Debian 系统(CentOS 类似但命令略有不同)。


一、启用 rewrite 模块

sudo a2enmod rewrite

执行后会提示你重启 Apache。


二、重启 Apache

sudo systemctl restart apache2

或(老版本):

sudo service apache2 restart

三、确认模块已启用

apache2ctl -M | grep rewrite

看到 rewrite_module (shared) 表示已开启。


四、允许 .htaccess 使用重写(很重要)

默认 Apache 可能不允许目录使用 .htaccess 中的重写规则。

编辑站点配置文件(例如):

sudo nano /etc/apache2/sites-available/000-default.conf

在 <VirtualHost> 中加入或修改为:

<Directory /var/www/html>
    AllowOverride All
</Directory>

保存后重启 Apache:

sudo systemctl restart apache2

五、示例 .htaccess

RewriteEngine On
RewriteRule ^test$ index.php [L]

六、CentOS / RHEL 补充

sudo vi /etc/httpd/conf/httpd.conf

确保:

LoadModule rewrite_module modules/mod_rewrite.so

并设置:

AllowOverride All

然后:

sudo systemctl restart httpd

如果你是在 Docker、宝塔、或某个具体框架(Laravel / ThinkPHP) 下使用,可以告诉我,我可以给你更针对性的配置。

0 踩