在 Apache2 中开启 URL Rewrite(重写),通常步骤如下(以 Ubuntu/Debian 为例,CentOS 类似):
sudo a2enmod rewrite
启用后重启 Apache:
sudo systemctl restart apache2
(CentOS 一般是 httpd,命令为 systemctl restart httpd)
编辑站点配置文件,例如:
sudo nano /etc/apache2/sites-available/000-default.conf
在 <VirtualHost> 或 <Directory> 中确保有:
<Directory /var/www/html>
AllowOverride All
</Directory>
⚠️ 关键点:AllowOverride None 会导致 .htaccess 不生效,必须改为 All
在网站根目录创建或编辑 .htaccess:
RewriteEngine On
# 示例:隐藏 index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
sudo tail -f /var/log/apache2/error.log
✅ 重写不生效?
rewrite 模块AllowOverride 不是 All.htaccess 文件位置不对如果你用的是 特定框架(Laravel / ThinkPHP / WordPress),我可以给你对应的重写规则。