温馨提示×

ubuntu apache2怎么开重写

小樊
41
2026-09-05 06:41:56
栏目: 智能运维

在 Ubuntu 上给 Apache2 开启 Rewrite(重写,mod_rewrite),一般按下面步骤来:


1. 启用 rewrite 模块

sudo a2enmod rewrite

启用后重启 Apache:

sudo systemctl restart apache2

2. 修改 Apache 配置,允许 .htaccess 重写

默认情况下,Apache 可能不允许目录使用 .htaccess 重写规则。

方法一:修改虚拟主机配置(推荐)

编辑你的站点配置,例如:

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

<VirtualHost *:80> 里加上:

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

保存后重启:

sudo systemctl restart apache2

方法二:修改 apache2.conf(不推荐全局)

sudo nano /etc/apache2/apache2.conf

找到:

<Directory /var/www/>
    AllowOverride None

改成:

AllowOverride All

然后:

sudo systemctl restart apache2

3. 使用 .htaccess 测试 Rewrite

在网站根目录创建 .htaccess

sudo nano /var/www/html/.htaccess

示例(隐藏 index.php):

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

4. 常见问题排查

  • 404 / 规则不生效 → 检查 AllowOverride All
  • 500 错误 → 检查 .htaccess 语法
  • 查看错误日志:
sudo tail -f /var/log/apache2/error.log

如果你是用 Laravel / WordPress / ThinkPHP 等框架,我可以给你对应的具体重写规则。

0