在Apache服务器上配置SSL证书

一、前提条件

  1. 你已经安装好 Apache
  2. 你已经有 SSL 证书文件(一般是 2 个)
    • xxx.crtxxx.pem(证书公钥)
    • xxx.key(证书私钥)
  3. 服务器开放 443 端口(HTTPS 默认端口)

二、第一步:开启 Apache SSL 模块

Linux(CentOS)

bash
运行
yum install mod_ssl -y

Linux(Ubuntu/Debian)

bash
运行
a2enmod ssl
a2enmod rewrite
systemctl restart apache2

Windows(XAMPP)

打开 xampp/apache/conf/httpd.conf

找到这两行,去掉前面的 #

apache
LoadModule ssl_module modules/mod_ssl.so
LoadModule rewrite_module modules/mod_rewrite.so

三、第二步:上传 / 放置证书

创建一个专门放证书的目录:

Linux

bash
运行
mkdir -p /etc/httpd/ssl
把证书放到:
plaintext
/etc/httpd/ssl/xxx.crt
/etc/httpd/ssl/xxx.key

Windows(XAMPP)

plaintext
xampp/apache/conf/ssl/xxx.crt
xampp/apache/conf/ssl/xxx.key

四、第三步:配置 HTTPS 虚拟主机(核心)

Linux(CentOS)

编辑文件:
bash
运行
vim /etc/httpd/conf.d/ssl.conf

Linux(Ubuntu)

bash
运行
vim /etc/apache2/sites-available/default-ssl.conf

Windows(XAMPP)

编辑:
plaintext
xampp/apache/conf/extra/httpd-ssl.conf

把下面配置直接复制进去(改 3 个路径即可)

apache
<VirtualHost *:443>
    # 你的域名
    ServerName www.yourdomain.com

    # 网站根目录(和 http 保持一致)
    DocumentRoot /var/www/html

    # 开启 SSL
    SSLEngine on

    # 证书路径 ↓↓↓ 这里改成你自己的证书路径
    SSLCertificateFile /etc/httpd/ssl/xxx.crt
    SSLCertificateKeyFile /etc/httpd/ssl/xxx.key

    # 日志
    ErrorLog /var/log/httpd/ssl-error.log
    CustomLog /var/log/httpd/ssl-access.log combined
</VirtualHost>

五、第四步:重启 Apache 生效

Linux(CentOS)

bash
运行
systemctl restart httpd

Linux(Ubuntu)

bash
运行
systemctl restart apache2

Windows(XAMPP)

点 Stop → Start Apache

六、第五步(必做):HTTP 自动跳转 HTTPS

让用户访问 http:// 时自动跳转到 https://
在 Apache 配置文件里加:
apache
<VirtualHost *:80>
    ServerName www.yourdomain.com
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [L,R=301]
</VirtualHost>
重启 Apache 即可。

七、测试是否成功

浏览器打开:
plaintext
https://你的域名
左边出现 小锁图标 = 配置成功 ✅

八、常见问题

  1. 443 端口无法访问

    去服务器安全组 / 防火墙开放 443 端口

  2. 配置后 Apache 启动失败

    证书路径写错、证书内容损坏

  3. 浏览器提示不安全

    证书不匹配、域名不一致


总结

  1. 开启 ssl 模块
  2. 放置 .crt.key 证书
  3. 配置 443 虚拟主机
  4. 设置 80 端口自动跳转 HTTPS
  5. 重启 Apache 完成
上一篇 交换机通过普通端口级联时,是怎么通讯的?
下一篇 浪潮服务器系统下重置BMC密码方法LINUX