温馨提示×

centos apache如何重定向

小樊
44
2026-09-30 03:00:12
栏目: 智能运维

在 CentOS 上,Apache 的重定向通常通过 mod_rewrite 或 Redirect / RedirectMatch 指令来实现。下面按常见场景说明。


一、确认 Apache 已启用重写模块(用于 rewrite)

CentOS 一般使用 httpd:

httpd -M | grep rewrite

如果没有 rewrite_module,启用它:

sudo vi /etc/httpd/conf.modules.d/00-base.conf

确保有:

LoadModule rewrite_module modules/mod_rewrite.so

重启 Apache:

sudo systemctl restart httpd

二、在虚拟主机或目录中配置重定向

1️⃣ 简单重定向(推荐,不使用 rewrite)

域名重定向到新域名

<VirtualHost *:80>
    ServerName old.example.com
    Redirect 301 / http://new.example.com/
</VirtualHost>

目录重定向

Redirect 301 /old/ http://example.com/new/

2️⃣ HTTP → HTTPS 重定向

<VirtualHost *:80>
    ServerName example.com
    Redirect 301 / https://example.com/
</VirtualHost>

3️⃣ 使用 mod_rewrite(更灵活)

在网站根目录或虚拟主机中:

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/html

    <Directory /var/www/html>
        AllowOverride All
        Require all granted
    </Directory>

    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

如果使用 .htaccess,需确保 AllowOverride All


4️⃣ 使用 .htaccess 重定向(常见)

编辑网站目录下的 .htaccess:

RewriteEngine On

# 旧页面重定向
RewriteRule ^oldpage\.html$ /newpage.html [R=301,L]

# 全站 http -> https
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

三、配置后必须操作

sudo systemctl restart httpd
# 或
sudo systemctl reload httpd

四、常见错误排查

  • 重定向循环 → 检查是否同时配置了 http 和 https 的 rewrite
  • 不生效 → 检查 AllowOverride 和 mod_rewrite
  • 缓存问题 → 清除浏览器缓存或使用隐身窗口

如果你能说明 具体重定向需求(如:域名跳转、路径跳转、带参数跳转),我可以给你更精确的 CentOS Apache 配置示例。

0 踩