在 Apache2 中开启 重写模块(mod_rewrite) 的方法如下,适用于 Ubuntu / Debian 系统(CentOS 类似但命令略有不同)。
sudo a2enmod rewrite
执行后会提示你重启 Apache。
sudo systemctl restart apache2
或(老版本):
sudo service apache2 restart
apache2ctl -M | grep rewrite
看到 rewrite_module (shared) 表示已开启。
默认 Apache 可能不允许目录使用 .htaccess 中的重写规则。
编辑站点配置文件(例如):
sudo nano /etc/apache2/sites-available/000-default.conf
在 <VirtualHost> 中加入或修改为:
<Directory /var/www/html>
AllowOverride All
</Directory>
保存后重启 Apache:
sudo systemctl restart apache2
RewriteEngine On
RewriteRule ^test$ index.php [L]
sudo vi /etc/httpd/conf/httpd.conf
确保:
LoadModule rewrite_module modules/mod_rewrite.so
并设置:
AllowOverride All
然后:
sudo systemctl restart httpd
如果你是在 Docker、宝塔、或某个具体框架(Laravel / ThinkPHP) 下使用,可以告诉我,我可以给你更针对性的配置。