温馨提示×

CentOS Apache怎么设置301重定向

小樊
54
2026-07-20 09:35:07
栏目: 智能运维

在 CentOS 上通过 Apache 设置 301 重定向,常见做法有几种,下面按使用场景给你最实用的配置方式(适用于 CentOS 7 / 8 / Stream,Apache 2.4)。


一、确认 Apache 已启用必要模块

301 重定向依赖 mod_alias 或 mod_rewrite,一般默认已启用。

httpd -M | grep alias
httpd -M | grep rewrite

如果没有启用:

vi /etc/httpd/conf/httpd.conf

确保以下行未被注释:

LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so

二、方式一:使用 Redirect(最简单,推荐)

1️⃣ 单个域名重定向(http → https)

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com

    Redirect 301 / https://example.com/
</VirtualHost>

✅ 特点:

  • 全站 301
  • 简单稳定
  • 推荐用于域名跳转

2️⃣ 重定向到带 www 的域名

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

三、方式二:使用 .htaccess(适合虚拟主机)

1️⃣ 启用 .htaccess

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

2️⃣ 编辑 .htaccess

vi /var/www/html/.htaccess

强制 HTTPS(最常用)

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

不带 www 跳转到带 www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

四、方式三:VirtualHost + Rewrite(服务器级,性能最好)

<VirtualHost *:80>
    ServerName example.com
    RewriteEngine On
    RewriteRule ^(.*)$ https://example.com$1 [L,R=301]
</VirtualHost>

五、重启 Apache 生效

systemctl restart httpd

或:

systemctl reload httpd

六、测试是否生效

curl -I http://example.com

应看到:

HTTP/1.1 301 Moved Permanently
Location: https://example.com/

七、常见错误排查

❌ 重定向循环
✅ 检查 HTTPS 虚拟主机是否又跳回 HTTP

❌ .htaccess 无效
✅ 确认 AllowOverride All

❌ SELinux 干扰(少见)

setenforce 0   # 临时测试

八、我可以帮你

你可以直接告诉我:

  • 是 http → https 还是 域名跳转
  • 是否使用 宝塔 / cPanel / 云服务器
  • 是 单站点还是多站点

我可以给你 完全匹配你环境的配置文件。

0 踩