How to Enable Apache Rewrite Module

Apache 的 mod_rewrite 是最强大的 URL 操作模块之一。使用 mod_rewrite,您可以重定向和重写 url,这对于在您的网站上实现 seo 友好的 URL 结构特别有用。在本文中,我们将引导您了解如何在基于 Debian 和基于 RHEL 的系统上在 Apache 中启用 mod 重写。

检查 mod_rewrite 是否启用

在启用 mod 重写之前,检查它是否已经激活。

apache2ctl -M | grep rewrite

OR

httpd -M | grep rewrite

如果你看到 rewrite_module (shared),那么 mod 重写已经启用。

开启 mod_rewrite

根据您的操作系统在 Apache web 服务器中启用 mod_rewrie 模块。

On Debian-based Systems

(1) 安装 Apache (如果尚未安装)

sudo apt update 
sudo apt install apache2

(2) 启用 mod_rewrite

sudo a2enmod rewrite

(3) 重启 Apache

sudo systemctl restart apache2

On RHEL-based Systems

(1) 安装 Apache (如果尚未安装)

sudo yum install httpd

(2) mod_rewrite 模块通常是默认启用的。如果没有,可以通过编辑 Apache 配置手动加载它。

sudo nano /etc/httpd/conf/httpd.conf

(3) 确保下面一行存在并且没有被注释掉

LoadModule rewrite_module modules/mod_rewrite.so

(4) 重启 Apache

sudo systemctl restart httpd

.htaccess 配置 mod_rewrite

要让 mod_rewrite 规则 在 .htaccess 文件中工作,必须确保目录配置允许重写。

Apache 的配置文件位置:

  • debian-based-systems: /etc/apache2/apache2.conf
  • rhel-based-systems: /etc/httpd/conf/httpd.conf

找到您的网站根目录并修改 AllowOverride 指令

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

在进行更改之后,一定要记得重新启动 Apache 服务。

测试 mod_rewrite

为了确保 mod_rewrite 能够正常工作,你可以在 .htaccess 文件中设置一个基本规则

nano /var/www/html/.htaccess

添加以下内容

RewriteEngine On
RewriteRule ^hello\.html$ welcome.html [R=302,L]

创建一个 welcome.html 文件

echo "Welcome, TecAdmin!" > /var/www/html/welcome.html

访问“http://your_server_ip/hello.html”应该将您重定向到“http://your_server_ip/welcome.html

我的开源项目

酷瓜云课堂-在线教育解决方案


鸠摩智首席音效师
475 声望9 粉丝

身强体健,龙精虎猛的活着。