温馨提示×

ubuntu apache2怎样开启重写

小樊
50
2026-09-05 07:43:56
栏目: 智能运维

在 Ubuntu 上开启 Apache2 的 URL Rewrite(重写),通常步骤如下:


一、启用 rewrite 模块

sudo a2enmod rewrite

启用后重启 Apache:

sudo systemctl restart apache2

二、修改 Apache 配置(关键)

1. 修改站点配置(推荐)

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

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

<VirtualHost *:80> 中添加或修改:

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

⚠️ 如果是其他目录,把 /var/www/html 改成你的项目目录

保存后重启 Apache:

sudo systemctl restart apache2

三、使用 .htaccess 重写规则(常见)

在项目根目录创建或编辑 .htaccess

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

四、常见问题排查

1. .htaccess 不生效

  • 确认 AllowOverride All
  • 确认 rewrite 模块已启用
  • 确认 .htaccess 在正确目录

查看是否启用模块:

apache2ctl -M | grep rewrite

2. 404 错误

  • 检查 DocumentRoot
  • 检查重写规则路径

五、示例(Laravel / ThinkPHP 等框架)

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

如果你是用 Nginx + ApacheDocker 或某个具体框架(如 Laravel / WordPress),可以告诉我,我可以给你更精确的配置。

0