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

Apache如何配置IP地址与www域名重定向到HTTPS主域名

现有配置的问题

  • 你修改后的配置存在重复的www.test.com域名绑定,第二个<VirtualHost *:80>段不会被匹配到,完全不生效
  • 绑定IP的虚拟主机段内的重写规则仅匹配域名请求,访问IP时无法触发重定向逻辑
  • 最初配置中存在无效ServerName ./install.sh的错误配置,且第二个80端口配置同时存在Redirect和Rewrite两套跳转规则,逻辑冲突,是导致www.test.com访问404的核心原因

可行的完整配置方案

# 80端口默认兜底段:处理IP访问、未绑定域名的请求,全部跳转至https://test.com
<VirtualHost *:80>
    ServerName 12.23.45.67
    RewriteEngine On
    RewriteRule ^ https://test.com%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

# 80端口域名处理段:处理test.com、www.test.com的HTTP请求,跳转至对应HTTPS
<VirtualHost *:80>
    <Directory /var/www/html/webserver/public>
        Allow From All
        AllowOverride All
        Options -Indexes
    </Directory>

    DocumentRoot /var/www/html/webserver/public
    ServerName test.com
    ServerAlias www.test.com

    RewriteEngine on
    RewriteCond %{SERVER_NAME} =www.test.com [OR]
    RewriteCond %{SERVER_NAME} =test.com
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

# 443端口配置,保持原有逻辑即可
<IfModule mod_ssl.c>
    <VirtualHost *:443>
        <Directory /var/www/html/webserver/public>
            Allow From All
            AllowOverride All
            Options -Indexes
        </Directory>
    
        DocumentRoot /var/www/html/webserver/public
        ServerName test.com
        ServerAlias www.test.com
        SSLCertificateFile /etc/letsencrypt/live/test.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/test.com/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf

        # 如需把www.test.com的HTTPS请求也跳转到test.com,可取消下面三行注释
        # RewriteEngine On
        # RewriteCond %{SERVER_NAME} =www.test.com
        # RewriteRule ^ https://test.com%{REQUEST_URI} [END,NE,R=permanent]
    </VirtualHost>
</IfModule>

验证步骤

  1. 配置修改完成后执行apachectl configtest检查语法是否正确
  2. 语法无报错后执行systemctl reload apache2(Debian/Ubuntu)或systemctl reload httpd(CentOS/RHEL)重载配置
  3. 测试前清理浏览器缓存,避免之前的永久重定向缓存影响测试结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:27:05