温馨提示×

centos lamp如何设置ssl

小樊
45
2026-10-15 00:46:48
栏目: 云计算

在 CentOS 上搭建 LAMP(Linux + Apache + MySQL/MariaDB + PHP) 并配置 SSL(HTTPS),常见做法有两种:

  1. 使用 Let’s Encrypt 免费证书(推荐)
  2. 使用自签名证书(测试用)

下面分别说明。


一、使用 Let’s Encrypt 免费 SSL(生产环境推荐)

1. 安装 EPEL 和 Certbot

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

CentOS 8 可用 dnf 替代 yum


2. 获取 SSL 证书

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

按提示操作:

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

3. 自动续期

certbot renew --dry-run

系统已默认配置定时任务(cron / systemd timer)


二、使用自签名证书(测试环境)

1. 生成私钥和证书

openssl req -x509 -nodes -days 365 \
-newkey rsa:2048 \
-keyout /etc/pki/tls/private/server.key \
-out /etc/pki/tls/certs/server.crt

按提示填写信息(Common Name 填域名或 IP)


2. 配置 Apache SSL

编辑或新建:

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

示例:

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

    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/server.crt
    SSLCertificateKeyFile /etc/pki/tls/private/server.key
</VirtualHost>

3. 启用并重启 Apache

systemctl restart httpd

三、防火墙与端口

确保 443 端口开放:

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

四、强制 HTTP 跳转到 HTTPS(可选)

在 Apache 配置中添加:

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

五、常见问题

  • 证书不受信任:自签名证书浏览器会警告,生产请用 Let’s Encrypt
  • Apache 未加载 SSL 模块:
    yum install mod_ssl
    
  • SELinux 阻止:
    setsebool -P httpd_can_network_connect 1
    

如果你能提供:

  • CentOS 版本(7 / 8 / Stream)
  • Apache 版本
  • 是否已有域名

我可以给你更精确的一步到位配置。

0 踩