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

Ubuntu 18.x下Apache2添加子域并实现HTTPS转发的问题

问题原因分析

你的问题出在主域配置冲突和子域配置的潜在疏漏上:

  1. 主域80端口存在两个ServerName example.com的VirtualHost,Apache会优先匹配第一个规则,当子域请求未被正确匹配时,会被主域的跳转逻辑强制导向www.example.com。
  2. 子域配置可能存在格式错误,或Apache未正确加载子域站点配置。
具体修复步骤

1. 修复主域HTTP(80端口)配置

打开example.com.conf,合并重复的VirtualHost,简化规则:

<VirtualHost *:80>
    ServerAdmin info@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog ${APACHE_LOG_DIR}/example.com.error.log
    CustomLog ${APACHE_LOG_DIR}/example.com.access.log combined

    RewriteEngine on
    # 处理example.com跳转到www.example.com并强制HTTPS
    RewriteCond %{SERVER_NAME} =example.com
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [END,NE,R=permanent]
    # 处理www.example.com直接跳转到HTTPS
    RewriteCond %{SERVER_NAME} =www.example.com
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

删除原来第一个单独的Redirect VirtualHost,避免规则冲突

2. 修正子域HTTP配置

确保development.example.com.conf配置逻辑正确(子域无需跳转到www):

<VirtualHost *:80>
    ServerAdmin info@example.com
    ServerName development.example.com
    DocumentRoot /var/www/development.example.com/public_html
    ErrorLog ${APACHE_LOG_DIR}/development.example.com.error.log
    CustomLog ${APACHE_LOG_DIR}/development.example.com.access.log combined

    RewriteEngine on
    # 仅强制子域跳转到HTTPS
    RewriteCond %{SERVER_NAME} =development.example.com
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

3. 修正子域HTTPS配置

打开development.example.com-le-ssl.conf,确保配置正确且证书覆盖子域:

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerAdmin info@example.com
    ServerName development.example.com
    DocumentRoot /var/www/development.example.com/public_html
    ErrorLog ${APACHE_LOG_DIR}/development.example.com.error.log
    CustomLog ${APACHE_LOG_DIR}/development.example.com.access.log combined
    Include /etc/letsencrypt/options-ssl-apache.conf
    # 确保证书路径正确,且证书包含development.example.com(通配符证书或单独申请的子域证书)
    SSLCertificateFile /etc/letsencrypt/live/development.example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/development.example.com/privkey.pem
</VirtualHost>
</IfModule>

4. 启用子域站点并重启Apache

执行以下命令完成配置加载:

# 启用子域HTTP站点
a2ensite development.example.com.conf
# 启用子域HTTPS站点
a2ensite development.example.com-le-ssl.conf
# 检查Apache配置语法
apache2ctl configtest
# 重启Apache服务
systemctl restart apache2

5. 验证DNS解析

确认development.example.com的DNS记录已正确指向服务器IP,避免因解析错误导致请求落到主域配置上。

额外排查点
  • 若问题仍存在,检查并禁用Apache默认站点(000-default.conf),避免默认站点接管未匹配的请求:
    a2dissite 000-default.conf
    systemctl restart apache2
    
  • 查看Apache错误日志(/var/log/apache2/error.log),排查是否有子域配置加载失败或证书相关错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:52:34