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

Apache VirtualHost特定目录重定向配置:HTTPS根域名跳转问题

Apache VirtualHost 重定向规则修复方案

问题原因

你当前配置的根路径重定向规则仅写在了*:80(HTTP)的虚拟主机块中,仅对HTTP请求生效。用户直接访问HTTPS协议的根域名时,请求走*:443(HTTPS)的虚拟主机块,该块内没有对应重定向规则,因此不会触发跳转。
此外原有配置直接使用Redirect /的规则会匹配所有前缀为/的路径,若直接放到443块中会导致/kd、/sub1下的所有请求都被重定向,出现逻辑冲突或循环跳转。

修复方案

调整重定向规则位置,使用RedirectMatch做精准路径匹配,避免影响其他路径的正常访问:

1. 调整80端口HTTP虚拟主机配置

统一将所有HTTP请求跳转至HTTPS,保留原请求路径,逻辑更简洁易维护:

<VirtualHost *:80>
    ServerName myDomain.de
    Redirect permanent / https://myDomain.de/
</VirtualHost>

2. 调整443端口HTTPS虚拟主机配置

在HTTPS块内新增两条精准重定向规则:

<VirtualHost _default_:443>
    ServerAdmin masterddgdgg@gmx.de
    ServerName myDomain.de
    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/myDomain.de-error.log
    CustomLog ${APACHE_LOG_DIR}/myDomain.de-access.log combined

    # 仅精准匹配根路径,跳转至sub1子目录
    RedirectMatch permanent ^/$ https://myDomain.de/sub1/
    # 仅匹配/kd路径,跳转至带后缀斜杠的地址
    RedirectMatch permanent ^/kd$ https://myDomain.de/kd/

    <IfModule mod_ssl.c>
        SSLCertificateFile /etc/letsencrypt/live/myDomain.de-0001/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/myDomain.de-0001/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf
    </IfModule>
</VirtualHost>

3. 原有Directory配置无需修改

<Directory "/var/www/html">
    Options -Indexes +FollowSymLinks +MultiViews
    AllowOverride All
    Require all granted
</Directory>

生效验证

  • 修改完成后先执行apache2ctl configtest检查配置语法,返回Syntax OK再执行下一步
  • 执行systemctl reload apache2重载Apache服务使配置生效
  • 清理浏览器缓存后测试访问,确认三种场景都正常:
    • 访问http://myDomain.de自动跳转至https://myDomain.de/sub1/
    • 访问https://myDomain.de自动跳转至https://myDomain.de/sub1/
    • 访问https://myDomain.de/kd自动跳转至https://myDomain.de/kd/

注意事项

如果sub1目录下的WordPress站点出现跳转异常,需要进入WordPress后台的设置页面,将*站点地址(Site URL)和WordPress地址(WordPress URL)*配置为https://myDomain.de/sub1,避免出现循环跳转。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:15:02