温馨提示×

apache2如何开启重写

小樊
46
2026-10-12 07:09:20
栏目: 编程语言

在 Apache2 中开启 URL Rewrite(重写),通常步骤如下(以 Ubuntu/Debian 为例,CentOS 类似):


一、启用 rewrite 模块

sudo a2enmod rewrite

启用后重启 Apache:

sudo systemctl restart apache2

(CentOS 一般是 httpd,命令为 systemctl restart httpd)


二、修改 Apache 配置允许重写

1. 修改虚拟主机或目录配置

编辑站点配置文件,例如:

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

在 <VirtualHost> 或 <Directory> 中确保有:

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

⚠️ 关键点:AllowOverride None 会导致 .htaccess 不生效,必须改为 All


三、使用 .htaccess 开启重写(常见方式)

在网站根目录创建或编辑 .htaccess:

RewriteEngine On

# 示例:隐藏 index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

四、验证是否生效

  1. 确保文件可访问
  2. 访问重写后的 URL
  3. 查看错误日志(如有问题):
sudo tail -f /var/log/apache2/error.log

五、常见问题

✅ 重写不生效?

  • 没启用 rewrite 模块
  • AllowOverride 不是 All
  • .htaccess 文件位置不对
  • 没重启 Apache

如果你用的是 特定框架(Laravel / ThinkPHP / WordPress),我可以给你对应的重写规则。

0 踩