温馨提示×

LNMP环境如何安装SSL

小樊
43
2026-08-06 01:50:06
栏目: 云计算

LNMP 环境(Linux + Nginx + MySQL + PHP) 中安装 SSL,通常是指 给 Nginx 配置 HTTPS 证书。下面按 最常见、最推荐 的方式一步步说明,适合新手和线上服务器。


一、准备条件

  1. 已安装 LNMP
    • Nginx 正常运行
    • 域名已解析到服务器 IP
  2. 域名
    • 例如:example.com
  3. 服务器端口
    • 80、443 已放行(云服务器安全组 + 防火墙)

二、方式一(最推荐):使用 Let’s Encrypt 免费 SSL(自动续签)

1️⃣ 安装 Certbot

CentOS 7/8

yum install -y epel-release
yum install -y certbot python3-certbot-nginx

Ubuntu / Debian

apt update
apt install -y certbot python3-certbot-nginx

2️⃣ 申请并自动配置 SSL

certbot --nginx -d example.com -d www.example.com

✅ 它会自动:

  • 申请证书
  • 修改 Nginx 配置
  • 配置 80 → 443
  • 设置自动续签

3️⃣ 验证自动续签

certbot renew --dry-run

Let’s Encrypt 证书:

  • ✅ 有效期:90 天
  • ✅ 自动续签(cron / systemd timer)

三、方式二:手动安装 SSL(已有证书)

如果你已有:

  • example.com.crt
  • example.com.key

1️⃣ 上传证书

mkdir -p /etc/nginx/ssl
cp example.com.crt /etc/nginx/ssl/
cp example.com.key /etc/nginx/ssl/

2️⃣ 修改 Nginx 站点配置

编辑配置文件(示例):

vim /etc/nginx/conf.d/example.conf

示例配置(HTTPS)

server {
    listen 443 ssl;
    server_name example.com www.example.com;

    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    root /home/wwwroot/example.com;
    index index.php index.html;

    location ~ \.php$ {
        fastcgi_pass   unix:/tmp/php-cgi.sock;
        fastcgi_index  index.php;
        include fastcgi.conf;
    }
}

# HTTP 自动跳转 HTTPS
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

3️⃣ 重载 Nginx

nginx -t
systemctl reload nginx

四、常见问题排查

❌ 443 无法访问

ss -lntp | grep 443

检查:

  • 云服务器安全组
  • 防火墙(firewalld / ufw)

❌ 证书不信任

  • 证书链不完整
  • 使用:
fullchain.crt

而不是 cert.crt


❌ LNMP 一键包用户

LNMP 自带 SSL 支持,可直接:

lnmp ssl add

五、推荐方案总结

场景 推荐方式
新站点 ✅ Let’s Encrypt
企业证书 手动安装
LNMP 一键包 lnmp ssl add
国内备案域名 可选国内 CA

如果你愿意,可以告诉我:

  • Linux 版本(CentOS / Ubuntu)
  • 是否使用 LNMP 一键包
  • 域名是否已解析

我可以给你 完全针对你服务器的命令

0