问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

如何启用 Apache Rewrite 重写模块?

创作时间:
作者:
@小白创作中心

如何启用 Apache Rewrite 重写模块?

引用
CSDN
1.
https://m.blog.csdn.net/xiaochong0302/article/details/145530649

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

检查 mod_rewrite 是否启用

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

apache2ctl -M | grep rewrite

或者

httpd -M | grep rewrite

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

开启 mod_rewrite

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

在Debian-based Systems上

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

    sudo apt update
    sudo apt install apache2
    
  2. 启用mod_rewrite

    sudo a2enmod rewrite
    
  3. 重启Apache

    sudo systemctl restart apache2
    

在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”

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号