温馨提示×

centos lamp如何开启https

小樊
52
2026-07-20 22:53:23
栏目: 智能运维

下面以 CentOS 7 + LAMP(Apache + MariaDB/MySQL + PHP) 为例,介绍如何开启 HTTPS(SSL),步骤清晰、可直接照做。


一、准备工作

1. 确认 Apache 已安装并运行

systemctl status httpd

如未安装:

yum install -y httpd
systemctl start httpd
systemctl enable httpd

2. 确认域名已解析

确保域名(如 example.com)已解析到服务器公网 IP。


二、安装 SSL 相关模块

1. 安装 mod_ssl

yum install -y mod_ssl

安装完成后会自动生成:

/etc/httpd/conf.d/ssl.conf

三、申请 SSL 证书(两种方式)


✅ 方式一:使用 Let’s Encrypt(推荐,免费)

1. 安装 certbot

yum install -y epel-release
yum install -y certbot python2-certbot-apache

2. 申请证书

certbot --apache -d example.com -d www.example.com

按提示操作:

  • 输入邮箱
  • 同意协议
  • 是否重定向 HTTP → HTTPS(建议选 2

自动配置 Apache,无需手动改配置文件


3. 自动续期(重要)

certbot renew --dry-run

Let’s Encrypt 证书 90 天有效期,系统会自动续期。


✅ 方式二:使用自签名证书(仅测试)

1. 生成私钥和证书

mkdir -p /etc/httpd/ssl
cd /etc/httpd/ssl

openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 \
-keyout server.key \
-out server.crt

填写信息示例:

Country Name: CN
State: Beijing
Organization Name: Test
Common Name: example.com

2. 配置 Apache SSL

编辑:

vim /etc/httpd/conf.d/ssl.conf

修改关键配置:

<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/html

    SSLEngine on
    SSLCertificateFile /etc/httpd/ssl/server.crt
    SSLCertificateKeyFile /etc/httpd/ssl/server.key

    <Directory /var/www/html>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

四、放行 HTTPS 端口

1. 防火墙

firewall-cmd --permanent --add-service=https
firewall-cmd --reload

2. 云服务器安全组

确保 TCP 443 已放行。


五、重启 Apache

systemctl restart httpd

六、HTTP 自动跳转 HTTPS(推荐)

编辑 HTTP 虚拟主机:

vim /etc/httpd/conf/httpd.conf

或新建:

vim /etc/httpd/conf.d/http-to-https.conf

内容:

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / https://example.com/
</VirtualHost>

重启 Apache:

systemctl restart httpd

七、验证

浏览器访问:

https://example.com

✅ 显示小锁即成功


八、常见问题

❌ 网站打不开 HTTPS

  • 检查 443 端口
  • 防火墙 / 安全组
  • SSL 证书路径是否正确

❌ Apache 启动失败

journalctl -xe
httpd -t

如果你用的是 CentOS 8 / Rocky / Alma / 宝塔 / LNMP,可以告诉我,我可以给你对应版本的具体方案。

0