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

如何使用Apache2实现HTTP转HTTPS及非www到www的全场景跳转

实现所有域名访问形式跳转至 https://www.example.com

前提准备

  • 确保Apache已启用mod_rewrite模块,执行以下命令开启:
    sudo a2enmod rewrite
    sudo systemctl restart apache2
    

配置虚拟主机

编辑Apache的虚拟主机配置文件(通常位于/etc/apache2/sites-available/目录下,比如example.com.conf),添加以下配置:

1. 处理HTTP(80端口)所有请求

将所有http://example.com和http://www.example.com的请求强制跳转至HTTPS带www的地址:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com

    RewriteEngine On
    # 301永久跳转至https://www.example.com
    RewriteRule ^(.*)$ https://www.example.com$1 [R=301,L]
</VirtualHost>

2. 处理HTTPS(443端口)请求

配置两个部分:正常服务https://www.example.com,以及将https://example.com的请求跳转至带www的地址(注:访问https://example.com时会先出现证书不匹配提示,确认后会完成跳转,这是因为您的SSL证书仅覆盖www.example.com):

# 正常提供https://www.example.com服务的虚拟主机
<VirtualHost *:443>
    ServerName www.example.com
    # 配置您的SSL证书路径
    SSLCertificateFile /path/to/your/www.example.com.crt
    SSLCertificateKeyFile /path/to/your/www.example.com.key
    # 若有中间证书,添加以下行
    # SSLCertificateChainFile /path/to/your/chain.crt

    # 网站根目录等正常配置
    DocumentRoot /var/www/example.com/public_html

    # 确保站内非www请求跳转
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\.example\.com$
    RewriteRule ^(.*)$ https://www.example.com$1 [R=301,L]
</VirtualHost>

# 处理https://example.com的跳转(证书不匹配但强制跳转)
<VirtualHost *:443>
    ServerName example.com
    # 使用已有www域名证书
    SSLCertificateFile /path/to/your/www.example.com.crt
    SSLCertificateKeyFile /path/to/your/www.example.com.key

    RewriteEngine On
    RewriteRule ^(.*)$ https://www.example.com$1 [R=301,L]
</VirtualHost>

生效配置

完成配置后,检查语法并重启Apache:

sudo apache2ctl configtest
sudo systemctl restart apache2

配置完成后,以下所有访问形式都会统一跳转至https://www.example.com:

  • example.com
  • www.example.com
  • https://example.com
  • http://example.com
  • http://www.example.com

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:52:37