如何启用 Apache 重写模块 ?

如何启用 Apache 重写模块 ?

精选文章moguli202025-03-03 11:14:5615A+A-

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 指令


    AllowOverride All

在进行更改之后,一定要记得重新启动 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”

我的开源项目

  • course-tencent-cloud(酷瓜云课堂 - gitee 仓库)
  • course-tencent-cloud(酷瓜云课堂 - github 仓库)
点击这里复制本文地址 以上内容由莫古技术网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

莫古技术网 © All Rights Reserved.  滇ICP备2024046894号-2