You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache虚拟主机:用mod_rewrite将别名子域名及HTTP重定向至HTTPS

解决Apache虚拟主机别名重定向问题

问题根源

  1. HTTPS别名无响应:当前配置仅作用于HTTP(80端口)虚拟主机,HTTPS(443端口)的虚拟主机未配置对应重定向规则,导致HTTPS协议的别名域名无法触发跳转。
  2. 双斜杠异常:原RewriteRule的路径拼接逻辑错误,导致重定向后URL末尾出现多余斜杠。

修正后的完整配置

1. HTTP(80端口)虚拟主机配置

<VirtualHost *:80>
    ServerName name.domain.com.br
    ServerAlias alias1.domain.com.br alias2.domain.com.br
    
    DocumentRoot /path/to/your/document/root
    ErrorLog /path/to/error.log
    CustomLog /path/to/access.log combined

    RewriteEngine On
    # 匹配别名域名,重定向到HTTPS主域名
    RewriteCond %{HTTP_HOST} ^alias1\.domain\.com\.br$ [OR]
    RewriteCond %{HTTP_HOST} ^alias2\.domain\.com\.br$
    RewriteRule ^ https://name.domain.com.br%{REQUEST_URI} [L,R=301]
    
    # 可选:如果需要主域名的HTTP请求也重定向到HTTPS,取消下方注释
    # RewriteCond %{HTTP_HOST} ^name\.domain\.com\.br$
    # RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

2. HTTPS(443端口)虚拟主机配置

<VirtualHost *:443>
    ServerName name.domain.com.br
    ServerAlias alias1.domain.com.br alias2.domain.com.br
    
    DocumentRoot /path/to/your/document/root
    ErrorLog /path/to/error.log
    CustomLog /path/to/access.log combined

    # SSL核心配置(必须存在,否则HTTPS请求无法正常处理)
    SSLEngine On
    SSLCertificateFile /path/to/certificate.crt
    SSLCertificateKeyFile /path/to/private.key
    SSLCertificateChainFile /path/to/chain.crt # 若证书包含链文件则添加

    RewriteEngine On
    # 匹配HTTPS协议下的别名域名,重定向到HTTPS主域名
    RewriteCond %{HTTP_HOST} ^alias1\.domain\.com\.br$ [OR]
    RewriteCond %{HTTP_HOST} ^alias2\.domain\.com\.br$
    RewriteRule ^ https://name.domain.com.br%{REQUEST_URI} [L,R=301]
</VirtualHost>

关键修改说明

  • 覆盖双协议:分别在80和443端口的虚拟主机中配置规则,确保HTTP/HTTPS协议的别名域名都能触发重定向。
  • 修复双斜杠:使用%{REQUEST_URI}自动获取请求路径,替代手动拼接逻辑,避免出现多余斜杠。若不需要保留原请求路径,可将规则改为RewriteRule ^ https://name.domain.com.br [L,R=301]。
  • 精确域名匹配:用转义后的正则表达式^alias1\.domain\.com\.br$精确匹配别名,避免意外匹配其他相似域名。
  • SSL依赖:HTTPS虚拟主机必须配置完整的SSL证书信息,否则HTTPS请求无法正常响应,重定向规则也不会生效。

操作注意事项

  1. 将配置中的/path/to/...替换为你的服务器实际路径。
  2. 测试阶段建议用R=302临时重定向,确认逻辑正常后再改为R=301永久重定向。
  3. 修改配置后重启Apache服务:sudo systemctl restart apache2(Debian/Ubuntu)或sudo systemctl restart httpd(CentOS/RHEL)。

内容的提问来源于stack exchange,提问作者Obede Macena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:00:47