温馨提示×

ubuntu apache如何开重写

小樊
42
2026-10-02 06:06:42
栏目: 智能运维

在 Ubuntu 上让 Apache 开启 URL Rewrite(重写),一般按下面步骤来:


一、启用 Apache 重写模块

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/yourproject),改成对应路径


2. (可选)修改 Apache 主配置

sudo nano /etc/apache2/apache2.conf

找到:

<Directory /var/www/>
    AllowOverride None

改成:

AllowOverride All

三、使用 .htaccess 重写规则

在项目根目录(如 /var/www/html)创建或编辑:

sudo nano /var/www/html/.htaccess

示例(隐藏 index.php):

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

四、重启 Apache

sudo systemctl restart apache2

五、常见问题排查

1. 重写不生效

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

2. 查看是否启用模块

apache2ctl -M | grep rewrite

如果你用的是 Laravel / ThinkPHP / WordPress,可以告诉我具体框架,我可以给你对应的 .htaccess 配置。

0 踩