Apache 2.4配置WWW转非WWW及HTTP转HTTPS时重定向过多
解决Apache 2.4重定向过多(Too Many Redirects)的问题
你的重定向循环问题核心出在HTTPS协议下的www域名没有被正确处理——当前配置只完成了HTTP到HTTPS的跳转,但没覆盖HTTPS场景下www转非www的逻辑,再加上AllowOverride All可能让.htaccess里的规则和主配置冲突,最终触发循环。下面是具体的修复步骤:
1. 补充443虚拟主机的重定向规则
修改你的sites-enabled/example.com.conf,在443端口的VirtualHost块中添加规则,专门处理HTTPS下的www域名跳转:
<VirtualHost *:443> ServerName example.com ServerAlias www.example.com # 新增:HTTPS下的www转非www永久重定向 RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC] RewriteRule ^(.*)$ https://example.com/$1 [R=301,L] DocumentRoot /var/www/example.com/public_html SSLEngine on SSLCertificateFile /etc/httpd/ssl/example.com.certificate.pem SSLCertificateKeyFile /etc/httpd/ssl/example.com.key.key <Directory /var/www/example.com/public_html/> Options +FollowSymlinks AllowOverride All Require all granted </Directory> ErrorLog /var/log/httpd/example.com.error.log CustomLog /var/log/httpd/example.com.access.log combined ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/example.com/public_html/$1 DirectoryIndex index.php index.html </VirtualHost>
2. 排查.htaccess的冲突规则
由于你开启了AllowOverride All,如果public_html目录下存在.htaccess文件,里面的反向重定向规则(比如非www转www)会和主配置逻辑打架,引发循环。你可以:
- 临时把
.htaccess重命名为.htaccess.bak,重启Apache后测试是否还会出现循环。 - 如果确实是
.htaccess的问题,删除里面冲突的重定向规则,确保所有跳转逻辑统一指向https://example.com。
3. 验证SSL证书的覆盖范围
确认你的SSL证书同时包含example.com和www.example.com(SAN证书或通配符证书均可),如果证书只覆盖了非www域名,访问https://www.example.com时会触发证书错误,部分浏览器的强制跳转逻辑也可能间接导致重定向循环。
4. 重启Apache并测试
完成修改后,重启Apache服务:
sudo systemctl restart httpd
然后清空浏览器缓存(或用隐私模式)测试所有访问组合:http://example.com、http://www.example.com、https://www.example.com,确认都能正确跳转到https://example.com且无循环错误。
内容的提问来源于stack exchange,提问作者eozzy
相关产品推荐
相关产品推荐

